diff --git a/auth.go b/auth.go index 5e030034b04..e5910b266f9 100644 --- a/auth.go +++ b/auth.go @@ -3,25 +3,28 @@ package influxdb import ( "context" "fmt" + + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) // AuthorizationKind is returned by (*Authorization).Kind(). const AuthorizationKind = "authorization" // ErrUnableToCreateToken sanitized error message for all errors when a user cannot create a token -var ErrUnableToCreateToken = &Error{ +var ErrUnableToCreateToken = &errors.Error{ Msg: "unable to create token", - Code: EInvalid, + Code: errors.EInvalid, } // Authorization is an authorization. 🎉 type Authorization struct { - ID ID `json:"id"` + ID platform.ID `json:"id"` Token string `json:"token"` Status Status `json:"status"` Description string `json:"description"` - OrgID ID `json:"orgID"` - UserID ID `json:"userID,omitempty"` + OrgID platform.ID `json:"orgID"` + UserID platform.ID `json:"userID,omitempty"` Permissions []Permission `json:"permissions"` CRUDLog } @@ -36,9 +39,9 @@ type AuthorizationUpdate struct { func (a *Authorization) Valid() error { for _, p := range a.Permissions { if p.Resource.OrgID != nil && *p.Resource.OrgID != a.OrgID { - return &Error{ + return &errors.Error{ Msg: fmt.Sprintf("permission %s is not for org id %s", p, a.OrgID), - Code: EInvalid, + Code: errors.EInvalid, } } } @@ -49,8 +52,8 @@ func (a *Authorization) Valid() error { // PermissionSet returns the set of permissions associated with the Authorization. func (a *Authorization) PermissionSet() (PermissionSet, error) { if !a.IsActive() { - return nil, &Error{ - Code: EUnauthorized, + return nil, &errors.Error{ + Code: errors.EUnauthorized, Msg: "token is inactive", } } @@ -69,7 +72,7 @@ func (a *Authorization) IsActive() bool { } // GetUserID returns the user id. -func (a *Authorization) GetUserID() ID { +func (a *Authorization) GetUserID() platform.ID { return a.UserID } @@ -77,7 +80,7 @@ func (a *Authorization) GetUserID() ID { func (a *Authorization) Kind() string { return AuthorizationKind } // Identifier returns the authorizations ID and is used for auditing. -func (a *Authorization) Identifier() ID { return a.ID } +func (a *Authorization) Identifier() platform.ID { return a.ID } // auth service op const ( @@ -92,7 +95,7 @@ const ( // AuthorizationService represents a service for managing authorization data. type AuthorizationService interface { // Returns a single authorization by ID. - FindAuthorizationByID(ctx context.Context, id ID) (*Authorization, error) + FindAuthorizationByID(ctx context.Context, id platform.ID) (*Authorization, error) // Returns a single authorization by Token. FindAuthorizationByToken(ctx context.Context, t string) (*Authorization, error) @@ -105,20 +108,20 @@ type AuthorizationService interface { CreateAuthorization(ctx context.Context, a *Authorization) error // UpdateAuthorization updates the status and description if available. - UpdateAuthorization(ctx context.Context, id ID, upd *AuthorizationUpdate) (*Authorization, error) + UpdateAuthorization(ctx context.Context, id platform.ID, upd *AuthorizationUpdate) (*Authorization, error) // Removes a authorization by token. - DeleteAuthorization(ctx context.Context, id ID) error + DeleteAuthorization(ctx context.Context, id platform.ID) error } // AuthorizationFilter represents a set of filter that restrict the returned results. type AuthorizationFilter struct { Token *string - ID *ID + ID *platform.ID - UserID *ID + UserID *platform.ID User *string - OrgID *ID + OrgID *platform.ID Org *string } diff --git a/authorization/error.go b/authorization/error.go index 2a538375faf..8247169e03b 100644 --- a/authorization/error.go +++ b/authorization/error.go @@ -3,64 +3,64 @@ package authorization import ( "fmt" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) var ( // ErrInvalidAuthID is used when the Authorization's ID cannot be encoded - ErrInvalidAuthID = &influxdb.Error{ - Code: influxdb.EInvalid, + ErrInvalidAuthID = &errors.Error{ + Code: errors.EInvalid, Msg: "authorization ID is invalid", } // ErrAuthNotFound is used when the specified auth cannot be found - ErrAuthNotFound = &influxdb.Error{ - Code: influxdb.ENotFound, + ErrAuthNotFound = &errors.Error{ + Code: errors.ENotFound, Msg: "authorization not found", } // NotUniqueIDError occurs when attempting to create an Authorization with an ID that already belongs to another one - NotUniqueIDError = &influxdb.Error{ - Code: influxdb.EConflict, + NotUniqueIDError = &errors.Error{ + Code: errors.EConflict, Msg: "ID already exists", } // ErrFailureGeneratingID occurs ony when the random number generator // cannot generate an ID in MaxIDGenerationN times. - ErrFailureGeneratingID = &influxdb.Error{ - Code: influxdb.EInternal, + ErrFailureGeneratingID = &errors.Error{ + Code: errors.EInternal, Msg: "unable to generate valid id", } // ErrTokenAlreadyExistsError is used when attempting to create an authorization // with a token that already exists - ErrTokenAlreadyExistsError = &influxdb.Error{ - Code: influxdb.EConflict, + ErrTokenAlreadyExistsError = &errors.Error{ + Code: errors.EConflict, Msg: "token already exists", } ) // ErrInvalidAuthIDError is used when a service was provided an invalid ID. -func ErrInvalidAuthIDError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInvalid, +func ErrInvalidAuthIDError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInvalid, Msg: "auth id provided is invalid", Err: err, } } // ErrInternalServiceError is used when the error comes from an internal system. -func ErrInternalServiceError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func ErrInternalServiceError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Err: err, } } // UnexpectedAuthIndexError is used when the error comes from an internal system. -func UnexpectedAuthIndexError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func UnexpectedAuthIndexError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("unexpected error retrieving auth index; Err: %v", err), } } diff --git a/authorization/http_client.go b/authorization/http_client.go index 48e0b77e105..6ce16c3a3d2 100644 --- a/authorization/http_client.go +++ b/authorization/http_client.go @@ -4,6 +4,8 @@ import ( "context" "errors" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/pkg/httpc" ) @@ -72,7 +74,7 @@ func (s *AuthorizationClientService) FindAuthorizationByToken(ctx context.Contex } // FindAuthorizationByID finds a single Authorization by its ID against a remote influx server. -func (s *AuthorizationClientService) FindAuthorizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) { +func (s *AuthorizationClientService) FindAuthorizationByID(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) { var b influxdb.Authorization err := s.Client. Get(prefixAuthorization, id.String()). @@ -85,7 +87,7 @@ func (s *AuthorizationClientService) FindAuthorizationByID(ctx context.Context, } // UpdateAuthorization updates the status and description if available. -func (s *AuthorizationClientService) UpdateAuthorization(ctx context.Context, id influxdb.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { +func (s *AuthorizationClientService) UpdateAuthorization(ctx context.Context, id platform.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { var res authResponse err := s.Client. PatchJSON(upd, prefixAuthorization, id.String()). @@ -99,7 +101,7 @@ func (s *AuthorizationClientService) UpdateAuthorization(ctx context.Context, id } // DeleteAuthorization removes a authorization by id. -func (s *AuthorizationClientService) DeleteAuthorization(ctx context.Context, id influxdb.ID) error { +func (s *AuthorizationClientService) DeleteAuthorization(ctx context.Context, id platform.ID) error { return s.Client. Delete(prefixAuthorization, id.String()). Do(ctx) diff --git a/authorization/http_server.go b/authorization/http_server.go index ab1e8f4a092..731fd50c8da 100644 --- a/authorization/http_server.go +++ b/authorization/http_server.go @@ -7,6 +7,9 @@ import ( "net/http" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/influxdata/influxdb/v2" @@ -17,11 +20,11 @@ import ( // TenantService is used to look up the Organization and User for an Authorization type TenantService interface { - FindOrganizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) + FindOrganizationByID(ctx context.Context, id platform.ID) (*influxdb.Organization, error) FindOrganization(ctx context.Context, filter influxdb.OrganizationFilter) (*influxdb.Organization, error) - FindUserByID(ctx context.Context, id influxdb.ID) (*influxdb.User, error) + FindUserByID(ctx context.Context, id platform.ID) (*influxdb.User, error) FindUser(ctx context.Context, filter influxdb.UserFilter) (*influxdb.User, error) - FindBucketByID(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) + FindBucketByID(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) } type AuthHandler struct { @@ -126,20 +129,20 @@ func getAuthorizedUser(r *http.Request, ts TenantService) (*influxdb.User, error type postAuthorizationRequest struct { Status influxdb.Status `json:"status"` - OrgID influxdb.ID `json:"orgID"` - UserID *influxdb.ID `json:"userID,omitempty"` + OrgID platform.ID `json:"orgID"` + UserID *platform.ID `json:"userID,omitempty"` Description string `json:"description"` Permissions []influxdb.Permission `json:"permissions"` } type authResponse struct { - ID influxdb.ID `json:"id"` + ID platform.ID `json:"id"` Token string `json:"token"` Status influxdb.Status `json:"status"` Description string `json:"description"` - OrgID influxdb.ID `json:"orgID"` + OrgID platform.ID `json:"orgID"` Org string `json:"org"` - UserID influxdb.ID `json:"userID"` + UserID platform.ID `json:"userID"` User string `json:"user"` Permissions []permissionResponse `json:"permissions"` Links map[string]string `json:"links"` @@ -181,7 +184,7 @@ func (h *AuthHandler) newAuthResponse(ctx context.Context, a *influxdb.Authoriza return res, nil } -func (p *postAuthorizationRequest) toInfluxdb(userID influxdb.ID) *influxdb.Authorization { +func (p *postAuthorizationRequest) toInfluxdb(userID platform.ID) *influxdb.Authorization { return &influxdb.Authorization{ OrgID: p.OrgID, Status: p.Status, @@ -250,24 +253,24 @@ func (p *postAuthorizationRequest) SetDefaults() { func (p *postAuthorizationRequest) Validate() error { if len(p.Permissions) == 0 { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "authorization must include permissions", } } for _, perm := range p.Permissions { if err := perm.Valid(); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } } if !p.OrgID.Valid() { - return &influxdb.Error{ - Err: influxdb.ErrInvalidID, - Code: influxdb.EInvalid, + return &errors.Error{ + Err: platform.ErrInvalidID, + Code: errors.EInvalid, Msg: "org id required", } } @@ -307,7 +310,7 @@ func (h *AuthHandler) newPermissionsResponse(ctx context.Context, ps []influxdb. if p.Resource.ID != nil { name, err := h.getNameForResource(ctx, p.Resource.Type, *p.Resource.ID) - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors.ErrorCode(err) == errors.ENotFound { continue } if err != nil { @@ -318,7 +321,7 @@ func (h *AuthHandler) newPermissionsResponse(ctx context.Context, ps []influxdb. if p.Resource.OrgID != nil { name, err := h.getNameForResource(ctx, influxdb.OrgsResourceType, *p.Resource.OrgID) - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors.ErrorCode(err) == errors.ENotFound { continue } if err != nil { @@ -330,13 +333,13 @@ func (h *AuthHandler) newPermissionsResponse(ctx context.Context, ps []influxdb. return res, nil } -func (h *AuthHandler) getNameForResource(ctx context.Context, resource influxdb.ResourceType, id influxdb.ID) (string, error) { +func (h *AuthHandler) getNameForResource(ctx context.Context, resource influxdb.ResourceType, id platform.ID) (string, error) { if err := resource.Valid(); err != nil { return "", err } if ok := id.Valid(); !ok { - return "", influxdb.ErrInvalidID + return "", platform.ErrInvalidID } switch resource { @@ -366,8 +369,8 @@ func (h *AuthHandler) getNameForResource(ctx context.Context, resource influxdb. func decodePostAuthorizationRequest(ctx context.Context, r *http.Request) (*postAuthorizationRequest, error) { a := &postAuthorizationRequest{} if err := json.NewDecoder(r.Body).Decode(a); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "invalid json structure", Err: err, } @@ -448,7 +451,7 @@ func decodeGetAuthorizationsRequest(ctx context.Context, r *http.Request) (*getA userID := qp.Get("userID") if userID != "" { - id, err := influxdb.IDFromString(userID) + id, err := platform.IDFromString(userID) if err != nil { return nil, err } @@ -462,7 +465,7 @@ func decodeGetAuthorizationsRequest(ctx context.Context, r *http.Request) (*getA orgID := qp.Get("orgID") if orgID != "" { - id, err := influxdb.IDFromString(orgID) + id, err := platform.IDFromString(orgID) if err != nil { return nil, err } @@ -476,7 +479,7 @@ func decodeGetAuthorizationsRequest(ctx context.Context, r *http.Request) (*getA authID := qp.Get("id") if authID != "" { - id, err := influxdb.IDFromString(authID) + id, err := platform.IDFromString(authID) if err != nil { return nil, err } @@ -489,7 +492,7 @@ func decodeGetAuthorizationsRequest(ctx context.Context, r *http.Request) (*getA func (h *AuthHandler) handleGetAuthorization(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - id, err := influxdb.IDFromString(chi.URLParam(r, "id")) + id, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { h.log.Info("Failed to decode request", zap.String("handler", "getAuthorization"), zap.Error(err)) h.api.Err(w, r, err) @@ -559,12 +562,12 @@ func (h *AuthHandler) handleUpdateAuthorization(w http.ResponseWriter, r *http.R } type updateAuthorizationRequest struct { - ID influxdb.ID + ID platform.ID *influxdb.AuthorizationUpdate } func decodeUpdateAuthorizationRequest(ctx context.Context, r *http.Request) (*updateAuthorizationRequest, error) { - id, err := influxdb.IDFromString(chi.URLParam(r, "id")) + id, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { return nil, err } @@ -582,7 +585,7 @@ func decodeUpdateAuthorizationRequest(ctx context.Context, r *http.Request) (*up // handleDeleteAuthorization is the HTTP handler for the DELETE /api/v2/authorizations/:id route. func (h *AuthHandler) handleDeleteAuthorization(w http.ResponseWriter, r *http.Request) { - id, err := influxdb.IDFromString(chi.URLParam(r, "id")) + id, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { h.log.Info("Failed to decode request", zap.String("handler", "deleteAuthorization"), zap.Error(err)) h.api.Err(w, r, err) diff --git a/authorization/http_server_test.go b/authorization/http_server_test.go index 14aba3028db..9675a4bf0bb 100644 --- a/authorization/http_server_test.go +++ b/authorization/http_server_test.go @@ -11,6 +11,9 @@ import ( "sort" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" @@ -68,19 +71,19 @@ func TestService_handlePostAuthorization(t *testing.T) { }, }, TenantService: &tenantService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ ID: id, Name: "u1", }, nil }, - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: id, Name: "o1", }, nil }, - FindBucketByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: id, Name: "b1", @@ -246,7 +249,7 @@ func TestService_handleGetAuthorization(t *testing.T) { name: "get a authorization by id", fields: fields{ AuthorizationService: &mock.AuthorizationService{ - FindAuthorizationByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) { + FindAuthorizationByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) { if id == itesting.MustIDBase16("020f755c3c082000") { return &influxdb.Authorization{ ID: itesting.MustIDBase16("020f755c3c082000"), @@ -258,7 +261,7 @@ func TestService_handleGetAuthorization(t *testing.T) { Resource: influxdb.Resource{ Type: influxdb.BucketsResourceType, OrgID: itesting.IDPtr(itesting.MustIDBase16("020f755c3c083000")), - ID: func() *influxdb.ID { + ID: func() *platform.ID { id := itesting.MustIDBase16("020f755c3c084000") return &id }(), @@ -273,19 +276,19 @@ func TestService_handleGetAuthorization(t *testing.T) { }, }, TenantService: &tenantService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ ID: id, Name: "u1", }, nil }, - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: id, Name: "o1", }, nil }, - FindBucketByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: id, Name: "b1", @@ -335,9 +338,9 @@ func TestService_handleGetAuthorization(t *testing.T) { name: "not found", fields: fields{ AuthorizationService: &mock.AuthorizationService{ - FindAuthorizationByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + FindAuthorizationByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) { + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: "authorization not found", } }, @@ -439,14 +442,14 @@ func TestService_handleGetAuthorizations(t *testing.T) { }, }, &tenantService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ ID: id, Name: id.String(), }, nil }, - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: id, Name: id.String(), @@ -531,16 +534,16 @@ func TestService_handleGetAuthorizations(t *testing.T) { }, }, &tenantService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { if id.String() == "2070616e656d2076" { return &influxdb.User{ ID: id, Name: id.String(), }, nil } - return nil, &influxdb.Error{} + return nil, &errors.Error{} }, - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: id, Name: id.String(), @@ -607,20 +610,20 @@ func TestService_handleGetAuthorizations(t *testing.T) { }, }, &tenantService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ ID: id, Name: id.String(), }, nil }, - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { if id.String() == "3070616e656d2076" { return &influxdb.Organization{ ID: id, Name: id.String(), }, nil } - return nil, &influxdb.Error{} + return nil, &errors.Error{} }, }, }, @@ -759,7 +762,7 @@ func TestService_handleDeleteAuthorization(t *testing.T) { name: "remove a authorization by id", fields: fields{ &mock.AuthorizationService{ - DeleteAuthorizationFn: func(ctx context.Context, id influxdb.ID) error { + DeleteAuthorizationFn: func(ctx context.Context, id platform.ID) error { if id == itesting.MustIDBase16("020f755c3c082000") { return nil } @@ -780,9 +783,9 @@ func TestService_handleDeleteAuthorization(t *testing.T) { name: "authorization not found", fields: fields{ &mock.AuthorizationService{ - DeleteAuthorizationFn: func(ctx context.Context, id influxdb.ID) error { - return &influxdb.Error{ - Code: influxdb.ENotFound, + DeleteAuthorizationFn: func(ctx context.Context, id platform.ID) error { + return &errors.Error{ + Code: errors.ENotFound, Msg: "authorization not found", } }, diff --git a/authorization/middleware_auth.go b/authorization/middleware_auth.go index a6b59ddc2ba..de0f3e9d2b6 100644 --- a/authorization/middleware_auth.go +++ b/authorization/middleware_auth.go @@ -4,6 +4,9 @@ import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/authorizer" ) @@ -50,7 +53,7 @@ func (s *AuthedAuthorizationService) FindAuthorizationByToken(ctx context.Contex return a, nil } -func (s *AuthedAuthorizationService) FindAuthorizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) { +func (s *AuthedAuthorizationService) FindAuthorizationByID(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) { a, err := s.s.FindAuthorizationByID(ctx, id) if err != nil { return nil, err @@ -74,7 +77,7 @@ func (s *AuthedAuthorizationService) FindAuthorizations(ctx context.Context, fil return authorizer.AuthorizeFindAuthorizations(ctx, as) } -func (s *AuthedAuthorizationService) UpdateAuthorization(ctx context.Context, id influxdb.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { +func (s *AuthedAuthorizationService) UpdateAuthorization(ctx context.Context, id platform.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { a, err := s.s.FindAuthorizationByID(ctx, id) if err != nil { return nil, err @@ -88,7 +91,7 @@ func (s *AuthedAuthorizationService) UpdateAuthorization(ctx context.Context, id return s.s.UpdateAuthorization(ctx, id, upd) } -func (s *AuthedAuthorizationService) DeleteAuthorization(ctx context.Context, id influxdb.ID) error { +func (s *AuthedAuthorizationService) DeleteAuthorization(ctx context.Context, id platform.ID) error { a, err := s.s.FindAuthorizationByID(ctx, id) if err != nil { return err @@ -106,10 +109,10 @@ func (s *AuthedAuthorizationService) DeleteAuthorization(ctx context.Context, id func VerifyPermissions(ctx context.Context, ps []influxdb.Permission) error { for _, p := range ps { if err := authorizer.IsAllowed(ctx, p); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, Msg: fmt.Sprintf("permission %s is not allowed", p), - Code: influxdb.EForbidden, + Code: errors.EForbidden, } } } diff --git a/authorization/middleware_auth_test.go b/authorization/middleware_auth_test.go index 840b96e5141..ddfa2d6ed9d 100644 --- a/authorization/middleware_auth_test.go +++ b/authorization/middleware_auth_test.go @@ -3,6 +3,8 @@ package authorization_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "sort" "testing" @@ -97,9 +99,9 @@ func TestAuthorizationService_ReadAuthorization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/0000000000000001/authorizations/000000000000000a is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, authorizations: []*influxdb.Authorization{}, }, @@ -125,9 +127,9 @@ func TestAuthorizationService_ReadAuthorization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:users/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, authorizations: []*influxdb.Authorization{}, }, @@ -137,7 +139,7 @@ func TestAuthorizationService_ReadAuthorization(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { m := &mock.AuthorizationService{} - m.FindAuthorizationByIDFn = func(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) { + m.FindAuthorizationByIDFn = func(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) { return &influxdb.Authorization{ ID: id, UserID: 1, @@ -252,9 +254,9 @@ func TestAuthorizationService_WriteAuthorization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/0000000000000001/authorizations/000000000000000a is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -279,9 +281,9 @@ func TestAuthorizationService_WriteAuthorization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:users/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -290,7 +292,7 @@ func TestAuthorizationService_WriteAuthorization(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { m := &mock.AuthorizationService{} - m.FindAuthorizationByIDFn = func(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) { + m.FindAuthorizationByIDFn = func(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) { return &influxdb.Authorization{ ID: id, UserID: 1, @@ -300,10 +302,10 @@ func TestAuthorizationService_WriteAuthorization(t *testing.T) { m.CreateAuthorizationFn = func(ctx context.Context, a *influxdb.Authorization) error { return nil } - m.DeleteAuthorizationFn = func(ctx context.Context, id influxdb.ID) error { + m.DeleteAuthorizationFn = func(ctx context.Context, id platform.ID) error { return nil } - m.UpdateAuthorizationFn = func(ctx context.Context, id influxdb.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { + m.UpdateAuthorizationFn = func(ctx context.Context, id platform.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { return nil, nil } // set up tenant service @@ -391,9 +393,9 @@ func TestAuthorizationService_CreateAuthorization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/0000000000000001/authorizations is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -418,9 +420,9 @@ func TestAuthorizationService_CreateAuthorization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:users/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -429,7 +431,7 @@ func TestAuthorizationService_CreateAuthorization(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { m := &mock.AuthorizationService{} - m.FindAuthorizationByIDFn = func(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) { + m.FindAuthorizationByIDFn = func(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) { return &influxdb.Authorization{ ID: id, UserID: 1, @@ -439,10 +441,10 @@ func TestAuthorizationService_CreateAuthorization(t *testing.T) { m.CreateAuthorizationFn = func(ctx context.Context, a *influxdb.Authorization) error { return nil } - m.DeleteAuthorizationFn = func(ctx context.Context, id influxdb.ID) error { + m.DeleteAuthorizationFn = func(ctx context.Context, id platform.ID) error { return nil } - m.UpdateAuthorizationFn = func(ctx context.Context, id influxdb.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { + m.UpdateAuthorizationFn = func(ctx context.Context, id platform.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { return nil, nil } // set up tenant service diff --git a/authorization/middleware_logging.go b/authorization/middleware_logging.go index 411a8ef164e..b93a623d3b2 100644 --- a/authorization/middleware_logging.go +++ b/authorization/middleware_logging.go @@ -5,6 +5,8 @@ import ( "fmt" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "go.uber.org/zap" ) @@ -36,7 +38,7 @@ func (l *AuthLogger) CreateAuthorization(ctx context.Context, a *influxdb.Author return l.authService.CreateAuthorization(ctx, a) } -func (l *AuthLogger) FindAuthorizationByID(ctx context.Context, id influxdb.ID) (a *influxdb.Authorization, err error) { +func (l *AuthLogger) FindAuthorizationByID(ctx context.Context, id platform.ID) (a *influxdb.Authorization, err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -74,7 +76,7 @@ func (l *AuthLogger) FindAuthorizations(ctx context.Context, filter influxdb.Aut return l.authService.FindAuthorizations(ctx, filter) } -func (l *AuthLogger) UpdateAuthorization(ctx context.Context, id influxdb.ID, upd *influxdb.AuthorizationUpdate) (a *influxdb.Authorization, err error) { +func (l *AuthLogger) UpdateAuthorization(ctx context.Context, id platform.ID, upd *influxdb.AuthorizationUpdate) (a *influxdb.Authorization, err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -86,7 +88,7 @@ func (l *AuthLogger) UpdateAuthorization(ctx context.Context, id influxdb.ID, up return l.authService.UpdateAuthorization(ctx, id, upd) } -func (l *AuthLogger) DeleteAuthorization(ctx context.Context, id influxdb.ID) (err error) { +func (l *AuthLogger) DeleteAuthorization(ctx context.Context, id platform.ID) (err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { diff --git a/authorization/middleware_metrics.go b/authorization/middleware_metrics.go index 55f3846acac..f4a2618242a 100644 --- a/authorization/middleware_metrics.go +++ b/authorization/middleware_metrics.go @@ -3,6 +3,8 @@ package authorization import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/metric" "github.com/prometheus/client_golang/prometheus" @@ -31,7 +33,7 @@ func (m *AuthMetrics) CreateAuthorization(ctx context.Context, a *influxdb.Autho return rec(err) } -func (m *AuthMetrics) FindAuthorizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) { +func (m *AuthMetrics) FindAuthorizationByID(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) { rec := m.rec.Record("find_authorization_by_id") a, err := m.authService.FindAuthorizationByID(ctx, id) return a, rec(err) @@ -47,13 +49,13 @@ func (m *AuthMetrics) FindAuthorizations(ctx context.Context, filter influxdb.Au return a, n, rec(err) } -func (m *AuthMetrics) UpdateAuthorization(ctx context.Context, id influxdb.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { +func (m *AuthMetrics) UpdateAuthorization(ctx context.Context, id platform.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { rec := m.rec.Record("update_authorization") a, err := m.authService.UpdateAuthorization(ctx, id, upd) return a, rec(err) } -func (m *AuthMetrics) DeleteAuthorization(ctx context.Context, id influxdb.ID) error { +func (m *AuthMetrics) DeleteAuthorization(ctx context.Context, id platform.ID) error { rec := m.rec.Record("delete_authorization") err := m.authService.DeleteAuthorization(ctx, id) return rec(err) diff --git a/authorization/mock_tenant.go b/authorization/mock_tenant.go index 576d62ecf46..0b047f8e6f8 100644 --- a/authorization/mock_tenant.go +++ b/authorization/mock_tenant.go @@ -3,20 +3,22 @@ package authorization import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) // tenantService is a mock implementation of an authorization.tenantService type tenantService struct { - FindUserByIDFn func(context.Context, influxdb.ID) (*influxdb.User, error) + FindUserByIDFn func(context.Context, platform.ID) (*influxdb.User, error) FindUserFn func(context.Context, influxdb.UserFilter) (*influxdb.User, error) - FindOrganizationByIDF func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) + FindOrganizationByIDF func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) FindOrganizationF func(ctx context.Context, filter influxdb.OrganizationFilter) (*influxdb.Organization, error) - FindBucketByIDFn func(context.Context, influxdb.ID) (*influxdb.Bucket, error) + FindBucketByIDFn func(context.Context, platform.ID) (*influxdb.Bucket, error) } // FindUserByID returns a single User by ID. -func (s *tenantService) FindUserByID(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { +func (s *tenantService) FindUserByID(ctx context.Context, id platform.ID) (*influxdb.User, error) { return s.FindUserByIDFn(ctx, id) } @@ -26,7 +28,7 @@ func (s *tenantService) FindUser(ctx context.Context, filter influxdb.UserFilter } //FindOrganizationByID calls FindOrganizationByIDF. -func (s *tenantService) FindOrganizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { +func (s *tenantService) FindOrganizationByID(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return s.FindOrganizationByIDF(ctx, id) } @@ -35,6 +37,6 @@ func (s *tenantService) FindOrganization(ctx context.Context, filter influxdb.Or return s.FindOrganizationF(ctx, filter) } -func (s *tenantService) FindBucketByID(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { +func (s *tenantService) FindBucketByID(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { return s.FindBucketByIDFn(ctx, id) } diff --git a/authorization/service.go b/authorization/service.go index 5558a7a5ef5..f65b0adcf5e 100644 --- a/authorization/service.go +++ b/authorization/service.go @@ -4,6 +4,9 @@ import ( "context" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" "github.com/influxdata/influxdb/v2/rand" @@ -27,7 +30,7 @@ func NewService(st *Store, ts TenantService) influxdb.AuthorizationService { func (s *Service) CreateAuthorization(ctx context.Context, a *influxdb.Authorization) error { if err := a.Valid(); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -53,7 +56,7 @@ func (s *Service) CreateAuthorization(ctx context.Context, a *influxdb.Authoriza if a.Token == "" { token, err := s.tokenGenerator.Token() if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -69,7 +72,7 @@ func (s *Service) CreateAuthorization(ctx context.Context, a *influxdb.Authoriza }) } -func (s *Service) FindAuthorizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) { +func (s *Service) FindAuthorizationByID(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) { var a *influxdb.Authorization err := s.store.View(ctx, func(tx kv.Tx) error { auth, err := s.store.GetAuthorizationByID(ctx, tx, id) @@ -124,7 +127,7 @@ func (s *Service) FindAuthorizations(ctx context.Context, filter influxdb.Author return nil }) if err != nil { - return nil, 0, &influxdb.Error{ + return nil, 0, &errors.Error{ Err: err, } } @@ -143,7 +146,7 @@ func (s *Service) FindAuthorizations(ctx context.Context, filter influxdb.Author return nil }) if err != nil { - return nil, 0, &influxdb.Error{ + return nil, 0, &errors.Error{ Err: err, } } @@ -162,7 +165,7 @@ func (s *Service) FindAuthorizations(ctx context.Context, filter influxdb.Author }) if err != nil { - return nil, 0, &influxdb.Error{ + return nil, 0, &errors.Error{ Err: err, } } @@ -171,7 +174,7 @@ func (s *Service) FindAuthorizations(ctx context.Context, filter influxdb.Author } // UpdateAuthorization updates the status and description if available. -func (s *Service) UpdateAuthorization(ctx context.Context, id influxdb.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { +func (s *Service) UpdateAuthorization(ctx context.Context, id platform.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { var auth *influxdb.Authorization err := s.store.View(ctx, func(tx kv.Tx) error { a, e := s.store.GetAuthorizationByID(ctx, tx, id) @@ -183,8 +186,8 @@ func (s *Service) UpdateAuthorization(ctx context.Context, id influxdb.ID, upd * }) if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Err: err, } } @@ -209,7 +212,7 @@ func (s *Service) UpdateAuthorization(ctx context.Context, id influxdb.ID, upd * return auth, err } -func (s *Service) DeleteAuthorization(ctx context.Context, id influxdb.ID) error { +func (s *Service) DeleteAuthorization(ctx context.Context, id platform.ID) error { return s.store.Update(ctx, func(tx kv.Tx) (err error) { return s.store.DeleteAuthorization(ctx, tx, id) }) diff --git a/authorization/storage.go b/authorization/storage.go index e3a06b6135c..264fa27ab08 100644 --- a/authorization/storage.go +++ b/authorization/storage.go @@ -3,7 +3,9 @@ package authorization import ( "context" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2/kit/tracing" "github.com/influxdata/influxdb/v2/kv" "github.com/influxdata/influxdb/v2/snowflake" @@ -19,7 +21,7 @@ var ( type Store struct { kvStore kv.Store - IDGen influxdb.IDGenerator + IDGen platform.IDGenerator } func NewStore(kvStore kv.Store) (*Store, error) { @@ -56,7 +58,7 @@ func (s *Store) setup() error { // generateSafeID attempts to create ids for buckets // and orgs that are without backslash, commas, and spaces, BUT ALSO do not already exist. -func (s *Store) generateSafeID(ctx context.Context, tx kv.Tx, bucket []byte) (influxdb.ID, error) { +func (s *Store) generateSafeID(ctx context.Context, tx kv.Tx, bucket []byte) (platform.ID, error) { for i := 0; i < MaxIDGenerationN; i++ { id := s.IDGen.ID() @@ -75,19 +77,19 @@ func (s *Store) generateSafeID(ctx context.Context, tx kv.Tx, bucket []byte) (in continue } - return influxdb.InvalidID(), err + return platform.InvalidID(), err } - return influxdb.InvalidID(), ErrFailureGeneratingID + return platform.InvalidID(), ErrFailureGeneratingID } -func (s *Store) uniqueID(ctx context.Context, tx kv.Tx, bucket []byte, id influxdb.ID) error { +func (s *Store) uniqueID(ctx context.Context, tx kv.Tx, bucket []byte, id platform.ID) error { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() encodedID, err := id.Encode() if err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Err: err, } } diff --git a/authorization/storage_authorization.go b/authorization/storage_authorization.go index e9bc4d535ab..c689fe5765b 100644 --- a/authorization/storage_authorization.go +++ b/authorization/storage_authorization.go @@ -4,6 +4,9 @@ import ( "context" "encoding/json" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/buger/jsonparser" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" @@ -29,8 +32,8 @@ func encodeAuthorization(a *influxdb.Authorization) ([]byte, error) { case "": a.Status = influxdb.Active default: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unknown authorization status", } } @@ -72,8 +75,8 @@ func (s *Store) CreateAuthorization(ctx context.Context, tx kv.Tx, a *influxdb.A v, err := encodeAuthorization(a) if err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -89,8 +92,8 @@ func (s *Store) CreateAuthorization(ctx context.Context, tx kv.Tx, a *influxdb.A } if err := idx.Put(authIndexKey(a.Token), encodedID); err != nil { - return &influxdb.Error{ - Code: influxdb.EInternal, + return &errors.Error{ + Code: errors.EInternal, Err: err, } } @@ -101,7 +104,7 @@ func (s *Store) CreateAuthorization(ctx context.Context, tx kv.Tx, a *influxdb.A } if err := b.Put(encodedID, v); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -110,7 +113,7 @@ func (s *Store) CreateAuthorization(ctx context.Context, tx kv.Tx, a *influxdb.A } // GetAuthorization gets an authorization by its ID from the auth bucket in kv -func (s *Store) GetAuthorizationByID(ctx context.Context, tx kv.Tx, id influxdb.ID) (*influxdb.Authorization, error) { +func (s *Store) GetAuthorizationByID(ctx context.Context, tx kv.Tx, id platform.ID) (*influxdb.Authorization, error) { encodedID, err := id.Encode() if err != nil { return nil, ErrInvalidAuthID @@ -132,8 +135,8 @@ func (s *Store) GetAuthorizationByID(ctx context.Context, tx kv.Tx, id influxdb. a := &influxdb.Authorization{} if err := decodeAuthorization(v, a); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -150,16 +153,16 @@ func (s *Store) GetAuthorizationByToken(ctx context.Context, tx kv.Tx, token str // use the token to look up the authorization's ID idKey, err := idx.Get(authIndexKey(token)) if kv.IsNotFound(err) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: "authorization not found", } } - var id influxdb.ID + var id platform.ID if err := id.Decode(idKey); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -221,19 +224,19 @@ func (s *Store) forEachAuthorization(ctx context.Context, tx kv.Tx, pred kv.Curs } // UpdateAuthorization updates the status and description only of an authorization -func (s *Store) UpdateAuthorization(ctx context.Context, tx kv.Tx, id influxdb.ID, a *influxdb.Authorization) (*influxdb.Authorization, error) { +func (s *Store) UpdateAuthorization(ctx context.Context, tx kv.Tx, id platform.ID, a *influxdb.Authorization) (*influxdb.Authorization, error) { v, err := encodeAuthorization(a) if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } encodedID, err := a.ID.Encode() if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Err: err, } } @@ -244,8 +247,8 @@ func (s *Store) UpdateAuthorization(ctx context.Context, tx kv.Tx, id influxdb.I } if err := idx.Put(authIndexKey(a.Token), encodedID); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInternal, + return nil, &errors.Error{ + Code: errors.EInternal, Err: err, } } @@ -256,7 +259,7 @@ func (s *Store) UpdateAuthorization(ctx context.Context, tx kv.Tx, id influxdb.I } if err := b.Put(encodedID, v); err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -266,7 +269,7 @@ func (s *Store) UpdateAuthorization(ctx context.Context, tx kv.Tx, id influxdb.I } // DeleteAuthorization removes an authorization from storage -func (s *Store) DeleteAuthorization(ctx context.Context, tx kv.Tx, id influxdb.ID) error { +func (s *Store) DeleteAuthorization(ctx context.Context, tx kv.Tx, id platform.ID) error { a, err := s.GetAuthorizationByID(ctx, tx, id) if err != nil { return err @@ -332,7 +335,7 @@ func unique(ctx context.Context, tx kv.Tx, indexBucket, indexKey []byte) error { } // uniqueID returns nil if the ID provided is unique, returns an error otherwise -func uniqueID(ctx context.Context, tx kv.Tx, id influxdb.ID) error { +func uniqueID(ctx context.Context, tx kv.Tx, id platform.ID) error { encodedID, err := id.Encode() if err != nil { return ErrInvalidAuthID diff --git a/authorization/storage_authorization_test.go b/authorization/storage_authorization_test.go index f03a53cfcf8..62ea964f84a 100644 --- a/authorization/storage_authorization_test.go +++ b/authorization/storage_authorization_test.go @@ -3,6 +3,7 @@ package authorization_test import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" "reflect" "testing" @@ -18,10 +19,10 @@ func TestAuth(t *testing.T) { setup := func(t *testing.T, store *authorization.Store, tx kv.Tx) { for i := 1; i <= 10; i++ { err := store.CreateAuthorization(context.Background(), tx, &influxdb.Authorization{ - ID: influxdb.ID(i), + ID: platform.ID(i), Token: fmt.Sprintf("randomtoken%d", i), - OrgID: influxdb.ID(i), - UserID: influxdb.ID(i), + OrgID: platform.ID(i), + UserID: platform.ID(i), Status: influxdb.Active, }) @@ -53,10 +54,10 @@ func TestAuth(t *testing.T) { expected := []*influxdb.Authorization{} for i := 1; i <= 10; i++ { expected = append(expected, &influxdb.Authorization{ - ID: influxdb.ID(i), + ID: platform.ID(i), Token: fmt.Sprintf("randomtoken%d", i), - OrgID: influxdb.ID(i), - UserID: influxdb.ID(i), + OrgID: platform.ID(i), + UserID: platform.ID(i), Status: "active", }) } @@ -66,10 +67,10 @@ func TestAuth(t *testing.T) { // should not be able to create two authorizations with identical tokens err = store.CreateAuthorization(context.Background(), tx, &influxdb.Authorization{ - ID: influxdb.ID(1), + ID: platform.ID(1), Token: fmt.Sprintf("randomtoken%d", 1), - OrgID: influxdb.ID(1), - UserID: influxdb.ID(1), + OrgID: platform.ID(1), + UserID: platform.ID(1), }) if err == nil { t.Fatalf("expected to be unable to create authorizations with identical tokens") @@ -82,14 +83,14 @@ func TestAuth(t *testing.T) { results: func(t *testing.T, store *authorization.Store, tx kv.Tx) { for i := 1; i <= 10; i++ { expectedAuth := &influxdb.Authorization{ - ID: influxdb.ID(i), + ID: platform.ID(i), Token: fmt.Sprintf("randomtoken%d", i), - OrgID: influxdb.ID(i), - UserID: influxdb.ID(i), + OrgID: platform.ID(i), + UserID: platform.ID(i), Status: influxdb.Active, } - authByID, err := store.GetAuthorizationByID(context.Background(), tx, influxdb.ID(i)) + authByID, err := store.GetAuthorizationByID(context.Background(), tx, platform.ID(i)) if err != nil { t.Fatalf("Unexpectedly could not acquire Authorization by ID [Error]: %v", err) } @@ -115,14 +116,14 @@ func TestAuth(t *testing.T) { setup: setup, update: func(t *testing.T, store *authorization.Store, tx kv.Tx) { for i := 1; i <= 10; i++ { - auth, err := store.GetAuthorizationByID(context.Background(), tx, influxdb.ID(i)) + auth, err := store.GetAuthorizationByID(context.Background(), tx, platform.ID(i)) if err != nil { t.Fatalf("Could not get authorization [Error]: %v", err) } auth.Status = influxdb.Inactive - _, err = store.UpdateAuthorization(context.Background(), tx, influxdb.ID(i), auth) + _, err = store.UpdateAuthorization(context.Background(), tx, platform.ID(i), auth) if err != nil { t.Fatalf("Could not get updated authorization [Error]: %v", err) } @@ -131,16 +132,16 @@ func TestAuth(t *testing.T) { results: func(t *testing.T, store *authorization.Store, tx kv.Tx) { for i := 1; i <= 10; i++ { - auth, err := store.GetAuthorizationByID(context.Background(), tx, influxdb.ID(i)) + auth, err := store.GetAuthorizationByID(context.Background(), tx, platform.ID(i)) if err != nil { t.Fatalf("Could not get authorization [Error]: %v", err) } expectedAuth := &influxdb.Authorization{ - ID: influxdb.ID(i), + ID: platform.ID(i), Token: fmt.Sprintf("randomtoken%d", i), - OrgID: influxdb.ID(i), - UserID: influxdb.ID(i), + OrgID: platform.ID(i), + UserID: platform.ID(i), Status: influxdb.Inactive, } @@ -155,7 +156,7 @@ func TestAuth(t *testing.T) { setup: setup, update: func(t *testing.T, store *authorization.Store, tx kv.Tx) { for i := 1; i <= 10; i++ { - err := store.DeleteAuthorization(context.Background(), tx, influxdb.ID(i)) + err := store.DeleteAuthorization(context.Background(), tx, platform.ID(i)) if err != nil { t.Fatalf("Could not delete authorization [Error]: %v", err) } @@ -163,7 +164,7 @@ func TestAuth(t *testing.T) { }, results: func(t *testing.T, store *authorization.Store, tx kv.Tx) { for i := 1; i <= 10; i++ { - _, err := store.GetAuthorizationByID(context.Background(), tx, influxdb.ID(i)) + _, err := store.GetAuthorizationByID(context.Background(), tx, platform.ID(i)) if err == nil { t.Fatal("Authorization was not deleted correctly") } diff --git a/authorizer/agent.go b/authorizer/agent.go index 8c40eda8bb6..1b7d1967956 100644 --- a/authorizer/agent.go +++ b/authorizer/agent.go @@ -3,6 +3,9 @@ package authorizer import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) @@ -11,7 +14,7 @@ import ( type AuthAgent struct{} // OrgPermissions identifies if a user has access to the org by the specified action. -func (a *AuthAgent) OrgPermissions(ctx context.Context, orgID influxdb.ID, action influxdb.Action, rest ...influxdb.Action) error { +func (a *AuthAgent) OrgPermissions(ctx context.Context, orgID platform.ID, action influxdb.Action, rest ...influxdb.Action) error { for _, action := range append(rest, action) { var err error switch action { @@ -20,7 +23,7 @@ func (a *AuthAgent) OrgPermissions(ctx context.Context, orgID influxdb.ID, actio case influxdb.WriteAction: _, _, err = AuthorizeWriteOrg(ctx, orgID) default: - err = &influxdb.Error{Code: influxdb.EInvalid, Msg: "invalid action provided: " + string(action)} + err = &errors.Error{Code: errors.EInvalid, Msg: "invalid action provided: " + string(action)} } if err != nil { return err @@ -29,13 +32,13 @@ func (a *AuthAgent) OrgPermissions(ctx context.Context, orgID influxdb.ID, actio return nil } -func (a *AuthAgent) IsWritable(ctx context.Context, orgID influxdb.ID, resType influxdb.ResourceType) error { +func (a *AuthAgent) IsWritable(ctx context.Context, orgID platform.ID, resType influxdb.ResourceType) error { _, _, resTypeErr := AuthorizeOrgWriteResource(ctx, resType, orgID) _, _, orgErr := AuthorizeWriteOrg(ctx, orgID) if resTypeErr != nil && orgErr != nil { - return &influxdb.Error{ - Code: influxdb.EUnauthorized, + return &errors.Error{ + Code: errors.EUnauthorized, Msg: "not authorized to create " + string(resType), } } diff --git a/authorizer/agent_test.go b/authorizer/agent_test.go index 0859260d5fd..aa8254729df 100644 --- a/authorizer/agent_test.go +++ b/authorizer/agent_test.go @@ -2,6 +2,7 @@ package authorizer_test import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" "testing" "github.com/influxdata/influxdb/v2" @@ -17,7 +18,7 @@ func Test_Agent(t *testing.T) { tests := []struct { name string action influxdb.Action - orgID influxdb.ID + orgID platform.ID permissions []influxdb.Permission shouldErr bool }{ @@ -175,7 +176,7 @@ func Test_Agent(t *testing.T) { tests := []struct { name string resourceType influxdb.ResourceType - orgID influxdb.ID + orgID platform.ID permissions []influxdb.Permission shouldErr bool }{ diff --git a/authorizer/auth.go b/authorizer/auth.go index 32663effabc..c09ca0e03cf 100644 --- a/authorizer/auth.go +++ b/authorizer/auth.go @@ -4,6 +4,9 @@ import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) @@ -23,7 +26,7 @@ func NewAuthorizationService(s influxdb.AuthorizationService) *AuthorizationServ } // FindAuthorizationByID checks to see if the authorizer on context has read access to the id provided. -func (s *AuthorizationService) FindAuthorizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) { +func (s *AuthorizationService) FindAuthorizationByID(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) { a, err := s.s.FindAuthorizationByID(ctx, id) if err != nil { return nil, err @@ -78,7 +81,7 @@ func (s *AuthorizationService) CreateAuthorization(ctx context.Context, a *influ } // UpdateAuthorization checks to see if the authorizer on context has write access to the authorization provided. -func (s *AuthorizationService) UpdateAuthorization(ctx context.Context, id influxdb.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { +func (s *AuthorizationService) UpdateAuthorization(ctx context.Context, id platform.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { a, err := s.s.FindAuthorizationByID(ctx, id) if err != nil { return nil, err @@ -93,7 +96,7 @@ func (s *AuthorizationService) UpdateAuthorization(ctx context.Context, id influ } // DeleteAuthorization checks to see if the authorizer on context has write access to the authorization provided. -func (s *AuthorizationService) DeleteAuthorization(ctx context.Context, id influxdb.ID) error { +func (s *AuthorizationService) DeleteAuthorization(ctx context.Context, id platform.ID) error { a, err := s.s.FindAuthorizationByID(ctx, id) if err != nil { return err @@ -111,10 +114,10 @@ func (s *AuthorizationService) DeleteAuthorization(ctx context.Context, id influ func VerifyPermissions(ctx context.Context, ps []influxdb.Permission) error { for _, p := range ps { if err := IsAllowed(ctx, p); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, Msg: fmt.Sprintf("permission %s is not allowed", p), - Code: influxdb.EForbidden, + Code: errors.EForbidden, } } } diff --git a/authorizer/auth_test.go b/authorizer/auth_test.go index c75c37c93dc..d18abe4a3de 100644 --- a/authorizer/auth_test.go +++ b/authorizer/auth_test.go @@ -3,6 +3,8 @@ package authorizer_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "sort" "testing" @@ -93,9 +95,9 @@ func TestAuthorizationService_ReadAuthorization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/0000000000000001/authorizations/000000000000000a is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, authorizations: []*influxdb.Authorization{}, }, @@ -121,9 +123,9 @@ func TestAuthorizationService_ReadAuthorization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:users/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, authorizations: []*influxdb.Authorization{}, }, @@ -133,7 +135,7 @@ func TestAuthorizationService_ReadAuthorization(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { m := &mock.AuthorizationService{} - m.FindAuthorizationByIDFn = func(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) { + m.FindAuthorizationByIDFn = func(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) { return &influxdb.Authorization{ ID: id, UserID: 1, @@ -241,9 +243,9 @@ func TestAuthorizationService_WriteAuthorization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/0000000000000001/authorizations/000000000000000a is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -268,9 +270,9 @@ func TestAuthorizationService_WriteAuthorization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:users/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -279,7 +281,7 @@ func TestAuthorizationService_WriteAuthorization(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { m := &mock.AuthorizationService{} - m.FindAuthorizationByIDFn = func(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) { + m.FindAuthorizationByIDFn = func(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) { return &influxdb.Authorization{ ID: id, UserID: 1, @@ -289,10 +291,10 @@ func TestAuthorizationService_WriteAuthorization(t *testing.T) { m.CreateAuthorizationFn = func(ctx context.Context, a *influxdb.Authorization) error { return nil } - m.DeleteAuthorizationFn = func(ctx context.Context, id influxdb.ID) error { + m.DeleteAuthorizationFn = func(ctx context.Context, id platform.ID) error { return nil } - m.UpdateAuthorizationFn = func(ctx context.Context, id influxdb.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { + m.UpdateAuthorizationFn = func(ctx context.Context, id platform.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { return nil, nil } s := authorizer.NewAuthorizationService(m) @@ -372,9 +374,9 @@ func TestAuthorizationService_CreateAuthorization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/0000000000000001/authorizations is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -399,9 +401,9 @@ func TestAuthorizationService_CreateAuthorization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:users/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -410,7 +412,7 @@ func TestAuthorizationService_CreateAuthorization(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { m := &mock.AuthorizationService{} - m.FindAuthorizationByIDFn = func(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) { + m.FindAuthorizationByIDFn = func(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) { return &influxdb.Authorization{ ID: id, UserID: 1, @@ -420,10 +422,10 @@ func TestAuthorizationService_CreateAuthorization(t *testing.T) { m.CreateAuthorizationFn = func(ctx context.Context, a *influxdb.Authorization) error { return nil } - m.DeleteAuthorizationFn = func(ctx context.Context, id influxdb.ID) error { + m.DeleteAuthorizationFn = func(ctx context.Context, id platform.ID) error { return nil } - m.UpdateAuthorizationFn = func(ctx context.Context, id influxdb.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { + m.UpdateAuthorizationFn = func(ctx context.Context, id platform.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { return nil, nil } s := authorizer.NewAuthorizationService(m) diff --git a/authorizer/authorize.go b/authorizer/authorize.go index ab968101091..4bc61c71652 100644 --- a/authorizer/authorize.go +++ b/authorizer/authorize.go @@ -4,6 +4,9 @@ import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" icontext "github.com/influxdata/influxdb/v2/context" ) @@ -16,8 +19,8 @@ func isAllowedAll(a influxdb.Authorizer, permissions []influxdb.Permission) erro for _, p := range permissions { if !pset.Allowed(p) { - return &influxdb.Error{ - Code: influxdb.EUnauthorized, + return &errors.Error{ + Code: errors.EUnauthorized, Msg: fmt.Sprintf("%s is unauthorized", p), } } @@ -61,13 +64,13 @@ func IsAllowedAny(ctx context.Context, permissions []influxdb.Permission) error return nil } } - return &influxdb.Error{ - Code: influxdb.EUnauthorized, + return &errors.Error{ + Code: errors.EUnauthorized, Msg: fmt.Sprintf("none of %v is authorized", permissions), } } -func authorize(ctx context.Context, a influxdb.Action, rt influxdb.ResourceType, rid, oid *influxdb.ID) (influxdb.Authorizer, influxdb.Permission, error) { +func authorize(ctx context.Context, a influxdb.Action, rt influxdb.ResourceType, rid, oid *platform.ID) (influxdb.Authorizer, influxdb.Permission, error) { var p *influxdb.Permission var err error if rid != nil && oid != nil { @@ -89,7 +92,7 @@ func authorize(ctx context.Context, a influxdb.Action, rt influxdb.ResourceType, return auth, *p, isAllowed(auth, *p) } -func authorizeReadSystemBucket(ctx context.Context, bid, oid influxdb.ID) (influxdb.Authorizer, influxdb.Permission, error) { +func authorizeReadSystemBucket(ctx context.Context, bid, oid platform.ID) (influxdb.Authorizer, influxdb.Permission, error) { return AuthorizeReadOrg(ctx, oid) } @@ -98,7 +101,7 @@ func authorizeReadSystemBucket(ctx context.Context, bid, oid influxdb.ID) (influ // AuthorizeRead(ctx, influxdb.BucketsResourceType, b.ID, b.OrgID) // use: // AuthorizeReadBucket(ctx, b.Type, b.ID, b.OrgID) -func AuthorizeReadBucket(ctx context.Context, bt influxdb.BucketType, bid, oid influxdb.ID) (influxdb.Authorizer, influxdb.Permission, error) { +func AuthorizeReadBucket(ctx context.Context, bt influxdb.BucketType, bid, oid platform.ID) (influxdb.Authorizer, influxdb.Permission, error) { switch bt { case influxdb.BucketTypeSystem: return authorizeReadSystemBucket(ctx, bid, oid) @@ -109,54 +112,54 @@ func AuthorizeReadBucket(ctx context.Context, bt influxdb.BucketType, bid, oid i // AuthorizeRead authorizes the user in the context to read the specified resource (identified by its type, ID, and orgID). // NOTE: authorization will pass even if the user only has permissions for the resource type and organization ID only. -func AuthorizeRead(ctx context.Context, rt influxdb.ResourceType, rid, oid influxdb.ID) (influxdb.Authorizer, influxdb.Permission, error) { +func AuthorizeRead(ctx context.Context, rt influxdb.ResourceType, rid, oid platform.ID) (influxdb.Authorizer, influxdb.Permission, error) { return authorize(ctx, influxdb.ReadAction, rt, &rid, &oid) } // AuthorizeWrite authorizes the user in the context to write the specified resource (identified by its type, ID, and orgID). // NOTE: authorization will pass even if the user only has permissions for the resource type and organization ID only. -func AuthorizeWrite(ctx context.Context, rt influxdb.ResourceType, rid, oid influxdb.ID) (influxdb.Authorizer, influxdb.Permission, error) { +func AuthorizeWrite(ctx context.Context, rt influxdb.ResourceType, rid, oid platform.ID) (influxdb.Authorizer, influxdb.Permission, error) { return authorize(ctx, influxdb.WriteAction, rt, &rid, &oid) } // AuthorizeRead authorizes the user in the context to read the specified resource (identified by its type, ID). // NOTE: authorization will pass only if the user has a specific permission for the given resource. -func AuthorizeReadResource(ctx context.Context, rt influxdb.ResourceType, rid influxdb.ID) (influxdb.Authorizer, influxdb.Permission, error) { +func AuthorizeReadResource(ctx context.Context, rt influxdb.ResourceType, rid platform.ID) (influxdb.Authorizer, influxdb.Permission, error) { return authorize(ctx, influxdb.ReadAction, rt, &rid, nil) } // AuthorizeWrite authorizes the user in the context to write the specified resource (identified by its type, ID). // NOTE: authorization will pass only if the user has a specific permission for the given resource. -func AuthorizeWriteResource(ctx context.Context, rt influxdb.ResourceType, rid influxdb.ID) (influxdb.Authorizer, influxdb.Permission, error) { +func AuthorizeWriteResource(ctx context.Context, rt influxdb.ResourceType, rid platform.ID) (influxdb.Authorizer, influxdb.Permission, error) { return authorize(ctx, influxdb.WriteAction, rt, &rid, nil) } // AuthorizeOrgReadResource authorizes the given org to read the resources of the given type. // NOTE: this is pretty much the same as AuthorizeRead, in the case that the resource ID is ignored. // Use it in the case that you do not know which resource in particular you want to give access to. -func AuthorizeOrgReadResource(ctx context.Context, rt influxdb.ResourceType, oid influxdb.ID) (influxdb.Authorizer, influxdb.Permission, error) { +func AuthorizeOrgReadResource(ctx context.Context, rt influxdb.ResourceType, oid platform.ID) (influxdb.Authorizer, influxdb.Permission, error) { return authorize(ctx, influxdb.ReadAction, rt, nil, &oid) } // AuthorizeOrgWriteResource authorizes the given org to write the resources of the given type. // NOTE: this is pretty much the same as AuthorizeWrite, in the case that the resource ID is ignored. // Use it in the case that you do not know which resource in particular you want to give access to. -func AuthorizeOrgWriteResource(ctx context.Context, rt influxdb.ResourceType, oid influxdb.ID) (influxdb.Authorizer, influxdb.Permission, error) { +func AuthorizeOrgWriteResource(ctx context.Context, rt influxdb.ResourceType, oid platform.ID) (influxdb.Authorizer, influxdb.Permission, error) { return authorize(ctx, influxdb.WriteAction, rt, nil, &oid) } // AuthorizeCreate authorizes a user to create a resource of the given type for the given org. -func AuthorizeCreate(ctx context.Context, rt influxdb.ResourceType, oid influxdb.ID) (influxdb.Authorizer, influxdb.Permission, error) { +func AuthorizeCreate(ctx context.Context, rt influxdb.ResourceType, oid platform.ID) (influxdb.Authorizer, influxdb.Permission, error) { return AuthorizeOrgWriteResource(ctx, rt, oid) } // AuthorizeReadOrg authorizes the user to read the given org. -func AuthorizeReadOrg(ctx context.Context, oid influxdb.ID) (influxdb.Authorizer, influxdb.Permission, error) { +func AuthorizeReadOrg(ctx context.Context, oid platform.ID) (influxdb.Authorizer, influxdb.Permission, error) { return authorize(ctx, influxdb.ReadAction, influxdb.OrgsResourceType, &oid, nil) } // AuthorizeWriteOrg authorizes the user to write the given org. -func AuthorizeWriteOrg(ctx context.Context, oid influxdb.ID) (influxdb.Authorizer, influxdb.Permission, error) { +func AuthorizeWriteOrg(ctx context.Context, oid platform.ID) (influxdb.Authorizer, influxdb.Permission, error) { return authorize(ctx, influxdb.WriteAction, influxdb.OrgsResourceType, &oid, nil) } diff --git a/authorizer/authorize_find.go b/authorizer/authorize_find.go index 9fa9fe23cc0..70b1980eff1 100644 --- a/authorizer/authorize_find.go +++ b/authorizer/authorize_find.go @@ -3,6 +3,8 @@ package authorizer import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) @@ -18,10 +20,10 @@ func AuthorizeFindDBRPs(ctx context.Context, rs []*influxdb.DBRPMappingV2) ([]*i if err != nil { _, _, err = AuthorizeWrite(ctx, influxdb.BucketsResourceType, r.BucketID, r.OrganizationID) } - if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized { + if err != nil && errors.ErrorCode(err) != errors.EUnauthorized { return nil, 0, err } - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors.ErrorCode(err) == errors.EUnauthorized { continue } rrs = append(rrs, r) @@ -36,17 +38,17 @@ func AuthorizeFindAuthorizations(ctx context.Context, rs []*influxdb.Authorizati rrs := rs[:0] for _, r := range rs { _, _, err := AuthorizeRead(ctx, influxdb.AuthorizationsResourceType, r.ID, r.OrgID) - if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized { + if err != nil && errors.ErrorCode(err) != errors.EUnauthorized { return nil, 0, err } - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors.ErrorCode(err) == errors.EUnauthorized { continue } _, _, err = AuthorizeReadResource(ctx, influxdb.UsersResourceType, r.UserID) - if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized { + if err != nil && errors.ErrorCode(err) != errors.EUnauthorized { return nil, 0, err } - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors.ErrorCode(err) == errors.EUnauthorized { continue } rrs = append(rrs, r) @@ -61,10 +63,10 @@ func AuthorizeFindBuckets(ctx context.Context, rs []*influxdb.Bucket) ([]*influx rrs := rs[:0] for _, r := range rs { _, _, err := AuthorizeReadBucket(ctx, r.Type, r.ID, r.OrgID) - if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized { + if err != nil && errors.ErrorCode(err) != errors.EUnauthorized { return nil, 0, err } - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors.ErrorCode(err) == errors.EUnauthorized { continue } rrs = append(rrs, r) @@ -79,10 +81,10 @@ func AuthorizeFindDashboards(ctx context.Context, rs []*influxdb.Dashboard) ([]* rrs := rs[:0] for _, r := range rs { _, _, err := AuthorizeRead(ctx, influxdb.DashboardsResourceType, r.ID, r.OrganizationID) - if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized { + if err != nil && errors.ErrorCode(err) != errors.EUnauthorized { return nil, 0, err } - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors.ErrorCode(err) == errors.EUnauthorized { continue } rrs = append(rrs, r) @@ -97,10 +99,10 @@ func AuthorizeFindOrganizations(ctx context.Context, rs []*influxdb.Organization rrs := rs[:0] for _, r := range rs { _, _, err := AuthorizeReadOrg(ctx, r.ID) - if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized { + if err != nil && errors.ErrorCode(err) != errors.EUnauthorized { return nil, 0, err } - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors.ErrorCode(err) == errors.EUnauthorized { continue } rrs = append(rrs, r) @@ -115,10 +117,10 @@ func AuthorizeFindSources(ctx context.Context, rs []*influxdb.Source) ([]*influx rrs := rs[:0] for _, r := range rs { _, _, err := AuthorizeRead(ctx, influxdb.SourcesResourceType, r.ID, r.OrganizationID) - if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized { + if err != nil && errors.ErrorCode(err) != errors.EUnauthorized { return nil, 0, err } - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors.ErrorCode(err) == errors.EUnauthorized { continue } rrs = append(rrs, r) @@ -133,10 +135,10 @@ func AuthorizeFindTasks(ctx context.Context, rs []*influxdb.Task) ([]*influxdb.T rrs := rs[:0] for _, r := range rs { _, _, err := AuthorizeRead(ctx, influxdb.TasksResourceType, r.ID, r.OrganizationID) - if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized { + if err != nil && errors.ErrorCode(err) != errors.EUnauthorized { return nil, 0, err } - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors.ErrorCode(err) == errors.EUnauthorized { continue } rrs = append(rrs, r) @@ -151,10 +153,10 @@ func AuthorizeFindTelegrafs(ctx context.Context, rs []*influxdb.TelegrafConfig) rrs := rs[:0] for _, r := range rs { _, _, err := AuthorizeRead(ctx, influxdb.TelegrafsResourceType, r.ID, r.OrgID) - if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized { + if err != nil && errors.ErrorCode(err) != errors.EUnauthorized { return nil, 0, err } - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors.ErrorCode(err) == errors.EUnauthorized { continue } rrs = append(rrs, r) @@ -169,10 +171,10 @@ func AuthorizeFindUsers(ctx context.Context, rs []*influxdb.User) ([]*influxdb.U rrs := rs[:0] for _, r := range rs { _, _, err := AuthorizeReadResource(ctx, influxdb.UsersResourceType, r.ID) - if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized { + if err != nil && errors.ErrorCode(err) != errors.EUnauthorized { return nil, 0, err } - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors.ErrorCode(err) == errors.EUnauthorized { continue } rrs = append(rrs, r) @@ -187,10 +189,10 @@ func AuthorizeFindVariables(ctx context.Context, rs []*influxdb.Variable) ([]*in rrs := rs[:0] for _, r := range rs { _, _, err := AuthorizeRead(ctx, influxdb.VariablesResourceType, r.ID, r.OrganizationID) - if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized { + if err != nil && errors.ErrorCode(err) != errors.EUnauthorized { return nil, 0, err } - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors.ErrorCode(err) == errors.EUnauthorized { continue } rrs = append(rrs, r) @@ -205,10 +207,10 @@ func AuthorizeFindScrapers(ctx context.Context, rs []influxdb.ScraperTarget) ([] rrs := rs[:0] for _, r := range rs { _, _, err := AuthorizeRead(ctx, influxdb.ScraperResourceType, r.ID, r.OrgID) - if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized { + if err != nil && errors.ErrorCode(err) != errors.EUnauthorized { return nil, 0, err } - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors.ErrorCode(err) == errors.EUnauthorized { continue } rrs = append(rrs, r) @@ -223,10 +225,10 @@ func AuthorizeFindLabels(ctx context.Context, rs []*influxdb.Label) ([]*influxdb rrs := rs[:0] for _, r := range rs { _, _, err := AuthorizeRead(ctx, influxdb.LabelsResourceType, r.ID, r.OrgID) - if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized { + if err != nil && errors.ErrorCode(err) != errors.EUnauthorized { return nil, 0, err } - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors.ErrorCode(err) == errors.EUnauthorized { continue } rrs = append(rrs, r) @@ -241,10 +243,10 @@ func AuthorizeFindNotificationRules(ctx context.Context, rs []influxdb.Notificat rrs := rs[:0] for _, r := range rs { _, _, err := AuthorizeRead(ctx, influxdb.NotificationRuleResourceType, r.GetID(), r.GetOrgID()) - if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized { + if err != nil && errors.ErrorCode(err) != errors.EUnauthorized { return nil, 0, err } - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors.ErrorCode(err) == errors.EUnauthorized { continue } rrs = append(rrs, r) @@ -259,10 +261,10 @@ func AuthorizeFindNotificationEndpoints(ctx context.Context, rs []influxdb.Notif rrs := rs[:0] for _, r := range rs { _, _, err := AuthorizeRead(ctx, influxdb.NotificationEndpointResourceType, r.GetID(), r.GetOrgID()) - if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized { + if err != nil && errors.ErrorCode(err) != errors.EUnauthorized { return nil, 0, err } - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors.ErrorCode(err) == errors.EUnauthorized { continue } rrs = append(rrs, r) @@ -277,10 +279,10 @@ func AuthorizeFindChecks(ctx context.Context, rs []influxdb.Check) ([]influxdb.C rrs := rs[:0] for _, r := range rs { _, _, err := AuthorizeRead(ctx, influxdb.ChecksResourceType, r.GetID(), r.GetOrgID()) - if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized { + if err != nil && errors.ErrorCode(err) != errors.EUnauthorized { return nil, 0, err } - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors.ErrorCode(err) == errors.EUnauthorized { continue } rrs = append(rrs, r) diff --git a/authorizer/bucket.go b/authorizer/bucket.go index df1f3a35374..a3f91f199c7 100644 --- a/authorizer/bucket.go +++ b/authorizer/bucket.go @@ -3,6 +3,8 @@ package authorizer import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/tracing" ) @@ -23,7 +25,7 @@ func NewBucketService(s influxdb.BucketService) *BucketService { } // FindBucketByID checks to see if the authorizer on context has read access to the id provided. -func (s *BucketService) FindBucketByID(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { +func (s *BucketService) FindBucketByID(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -38,7 +40,7 @@ func (s *BucketService) FindBucketByID(ctx context.Context, id influxdb.ID) (*in } // FindBucketByName returns a bucket by name for a particular organization. -func (s *BucketService) FindBucketByName(ctx context.Context, orgID influxdb.ID, n string) (*influxdb.Bucket, error) { +func (s *BucketService) FindBucketByName(ctx context.Context, orgID platform.ID, n string) (*influxdb.Bucket, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -93,7 +95,7 @@ func (s *BucketService) CreateBucket(ctx context.Context, b *influxdb.Bucket) er } // UpdateBucket checks to see if the authorizer on context has write access to the bucket provided. -func (s *BucketService) UpdateBucket(ctx context.Context, id influxdb.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { +func (s *BucketService) UpdateBucket(ctx context.Context, id platform.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { b, err := s.s.FindBucketByID(ctx, id) if err != nil { return nil, err @@ -105,7 +107,7 @@ func (s *BucketService) UpdateBucket(ctx context.Context, id influxdb.ID, upd in } // DeleteBucket checks to see if the authorizer on context has write access to the bucket provided. -func (s *BucketService) DeleteBucket(ctx context.Context, id influxdb.ID) error { +func (s *BucketService) DeleteBucket(ctx context.Context, id platform.ID) error { b, err := s.s.FindBucketByID(ctx, id) if err != nil { return err diff --git a/authorizer/bucket_test.go b/authorizer/bucket_test.go index c14ebe5ed5c..05242efe5bb 100644 --- a/authorizer/bucket_test.go +++ b/authorizer/bucket_test.go @@ -3,6 +3,8 @@ package authorizer_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "sort" "testing" @@ -33,7 +35,7 @@ func TestBucketService_FindBucketByID(t *testing.T) { } type args struct { permission influxdb.Permission - id influxdb.ID + id platform.ID } type wants struct { err error @@ -49,7 +51,7 @@ func TestBucketService_FindBucketByID(t *testing.T) { name: "authorized to access id", fields: fields{ BucketService: &mock.BucketService{ - FindBucketByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: id, OrgID: 10, @@ -75,7 +77,7 @@ func TestBucketService_FindBucketByID(t *testing.T) { name: "unauthorized to access id", fields: fields{ BucketService: &mock.BucketService{ - FindBucketByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: id, OrgID: 10, @@ -94,9 +96,9 @@ func TestBucketService_FindBucketByID(t *testing.T) { id: 1, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/000000000000000a/buckets/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -179,9 +181,9 @@ func TestBucketService_FindBucket(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/000000000000000a/buckets/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -334,7 +336,7 @@ func TestBucketService_UpdateBucket(t *testing.T) { BucketService influxdb.BucketService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -351,13 +353,13 @@ func TestBucketService_UpdateBucket(t *testing.T) { name: "authorized to update bucket", fields: fields{ BucketService: &mock.BucketService{ - FindBucketByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: 1, OrgID: 10, }, nil }, - UpdateBucketFn: func(ctx context.Context, id influxdb.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { + UpdateBucketFn: func(ctx context.Context, id platform.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: 1, OrgID: 10, @@ -392,13 +394,13 @@ func TestBucketService_UpdateBucket(t *testing.T) { name: "unauthorized to update bucket", fields: fields{ BucketService: &mock.BucketService{ - FindBucketByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: 1, OrgID: 10, }, nil }, - UpdateBucketFn: func(ctx context.Context, id influxdb.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { + UpdateBucketFn: func(ctx context.Context, id platform.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: 1, OrgID: 10, @@ -419,9 +421,9 @@ func TestBucketService_UpdateBucket(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/buckets/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -445,7 +447,7 @@ func TestBucketService_DeleteBucket(t *testing.T) { BucketService influxdb.BucketService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -462,13 +464,13 @@ func TestBucketService_DeleteBucket(t *testing.T) { name: "authorized to delete bucket", fields: fields{ BucketService: &mock.BucketService{ - FindBucketByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: 1, OrgID: 10, }, nil }, - DeleteBucketFn: func(ctx context.Context, id influxdb.ID) error { + DeleteBucketFn: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -500,13 +502,13 @@ func TestBucketService_DeleteBucket(t *testing.T) { name: "unauthorized to delete bucket", fields: fields{ BucketService: &mock.BucketService{ - FindBucketByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: 1, OrgID: 10, }, nil }, - DeleteBucketFn: func(ctx context.Context, id influxdb.ID) error { + DeleteBucketFn: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -524,9 +526,9 @@ func TestBucketService_DeleteBucket(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/buckets/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -551,7 +553,7 @@ func TestBucketService_CreateBucket(t *testing.T) { } type args struct { permission influxdb.Permission - orgID influxdb.ID + orgID platform.ID } type wants struct { err error @@ -606,9 +608,9 @@ func TestBucketService_CreateBucket(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/buckets is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, diff --git a/authorizer/check.go b/authorizer/check.go index c5a5f66f151..e68675998f4 100644 --- a/authorizer/check.go +++ b/authorizer/check.go @@ -3,6 +3,8 @@ package authorizer import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -27,7 +29,7 @@ func NewCheckService(s influxdb.CheckService, urm influxdb.UserResourceMappingSe } // FindCheckByID checks to see if the authorizer on context has read access to the id provided. -func (s *CheckService) FindCheckByID(ctx context.Context, id influxdb.ID) (influxdb.Check, error) { +func (s *CheckService) FindCheckByID(ctx context.Context, id platform.ID) (influxdb.Check, error) { chk, err := s.s.FindCheckByID(ctx, id) if err != nil { return nil, err @@ -62,7 +64,7 @@ func (s *CheckService) FindCheck(ctx context.Context, filter influxdb.CheckFilte } // CreateCheck checks to see if the authorizer on context has write access to the global check resource. -func (s *CheckService) CreateCheck(ctx context.Context, chk influxdb.CheckCreate, userID influxdb.ID) error { +func (s *CheckService) CreateCheck(ctx context.Context, chk influxdb.CheckCreate, userID platform.ID) error { if _, _, err := AuthorizeCreate(ctx, influxdb.ChecksResourceType, chk.GetOrgID()); err != nil { return err } @@ -70,7 +72,7 @@ func (s *CheckService) CreateCheck(ctx context.Context, chk influxdb.CheckCreate } // UpdateCheck checks to see if the authorizer on context has write access to the check provided. -func (s *CheckService) UpdateCheck(ctx context.Context, id influxdb.ID, upd influxdb.CheckCreate) (influxdb.Check, error) { +func (s *CheckService) UpdateCheck(ctx context.Context, id platform.ID, upd influxdb.CheckCreate) (influxdb.Check, error) { chk, err := s.FindCheckByID(ctx, id) if err != nil { return nil, err @@ -82,7 +84,7 @@ func (s *CheckService) UpdateCheck(ctx context.Context, id influxdb.ID, upd infl } // PatchCheck checks to see if the authorizer on context has write access to the check provided. -func (s *CheckService) PatchCheck(ctx context.Context, id influxdb.ID, upd influxdb.CheckUpdate) (influxdb.Check, error) { +func (s *CheckService) PatchCheck(ctx context.Context, id platform.ID, upd influxdb.CheckUpdate) (influxdb.Check, error) { chk, err := s.FindCheckByID(ctx, id) if err != nil { return nil, err @@ -94,7 +96,7 @@ func (s *CheckService) PatchCheck(ctx context.Context, id influxdb.ID, upd influ } // DeleteCheck checks to see if the authorizer on context has write access to the check provided. -func (s *CheckService) DeleteCheck(ctx context.Context, id influxdb.ID) error { +func (s *CheckService) DeleteCheck(ctx context.Context, id platform.ID) error { chk, err := s.FindCheckByID(ctx, id) if err != nil { return err diff --git a/authorizer/check_test.go b/authorizer/check_test.go index 47f73d906b1..0a3ebfc69c5 100644 --- a/authorizer/check_test.go +++ b/authorizer/check_test.go @@ -3,6 +3,8 @@ package authorizer_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "sort" "testing" @@ -34,7 +36,7 @@ func TestCheckService_FindCheckByID(t *testing.T) { } type args struct { permission influxdb.Permission - id influxdb.ID + id platform.ID } type wants struct { err error @@ -50,7 +52,7 @@ func TestCheckService_FindCheckByID(t *testing.T) { name: "authorized to access id", fields: fields{ CheckService: &mock.CheckService{ - FindCheckByIDFn: func(ctx context.Context, id influxdb.ID) (influxdb.Check, error) { + FindCheckByIDFn: func(ctx context.Context, id platform.ID) (influxdb.Check, error) { return &check.Deadman{ Base: check.Base{ ID: id, @@ -78,7 +80,7 @@ func TestCheckService_FindCheckByID(t *testing.T) { name: "unauthorized to access id", fields: fields{ CheckService: &mock.CheckService{ - FindCheckByIDFn: func(ctx context.Context, id influxdb.ID) (influxdb.Check, error) { + FindCheckByIDFn: func(ctx context.Context, id platform.ID) (influxdb.Check, error) { return &check.Deadman{ Base: check.Base{ ID: id, @@ -99,9 +101,9 @@ func TestCheckService_FindCheckByID(t *testing.T) { id: 1, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/000000000000000a/checks/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -275,7 +277,7 @@ func TestCheckService_UpdateCheck(t *testing.T) { CheckService influxdb.CheckService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -292,7 +294,7 @@ func TestCheckService_UpdateCheck(t *testing.T) { name: "authorized to update check", fields: fields{ CheckService: &mock.CheckService{ - FindCheckByIDFn: func(ctx context.Context, id influxdb.ID) (influxdb.Check, error) { + FindCheckByIDFn: func(ctx context.Context, id platform.ID) (influxdb.Check, error) { return &check.Deadman{ Base: check.Base{ ID: 1, @@ -300,7 +302,7 @@ func TestCheckService_UpdateCheck(t *testing.T) { }, }, nil }, - UpdateCheckFn: func(ctx context.Context, id influxdb.ID, upd influxdb.CheckCreate) (influxdb.Check, error) { + UpdateCheckFn: func(ctx context.Context, id platform.ID, upd influxdb.CheckCreate) (influxdb.Check, error) { return &check.Deadman{ Base: check.Base{ ID: 1, @@ -337,7 +339,7 @@ func TestCheckService_UpdateCheck(t *testing.T) { name: "unauthorized to update check", fields: fields{ CheckService: &mock.CheckService{ - FindCheckByIDFn: func(ctx context.Context, id influxdb.ID) (influxdb.Check, error) { + FindCheckByIDFn: func(ctx context.Context, id platform.ID) (influxdb.Check, error) { return &check.Deadman{ Base: check.Base{ ID: 1, @@ -345,7 +347,7 @@ func TestCheckService_UpdateCheck(t *testing.T) { }, }, nil }, - UpdateCheckFn: func(ctx context.Context, id influxdb.ID, upd influxdb.CheckCreate) (influxdb.Check, error) { + UpdateCheckFn: func(ctx context.Context, id platform.ID, upd influxdb.CheckCreate) (influxdb.Check, error) { return &check.Deadman{ Base: check.Base{ ID: 1, @@ -368,9 +370,9 @@ func TestCheckService_UpdateCheck(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/checks/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -399,7 +401,7 @@ func TestCheckService_PatchCheck(t *testing.T) { CheckService influxdb.CheckService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -416,7 +418,7 @@ func TestCheckService_PatchCheck(t *testing.T) { name: "authorized to patch check", fields: fields{ CheckService: &mock.CheckService{ - FindCheckByIDFn: func(ctx context.Context, id influxdb.ID) (influxdb.Check, error) { + FindCheckByIDFn: func(ctx context.Context, id platform.ID) (influxdb.Check, error) { return &check.Deadman{ Base: check.Base{ ID: 1, @@ -424,7 +426,7 @@ func TestCheckService_PatchCheck(t *testing.T) { }, }, nil }, - PatchCheckFn: func(ctx context.Context, id influxdb.ID, upd influxdb.CheckUpdate) (influxdb.Check, error) { + PatchCheckFn: func(ctx context.Context, id platform.ID, upd influxdb.CheckUpdate) (influxdb.Check, error) { return &check.Deadman{ Base: check.Base{ ID: 1, @@ -461,7 +463,7 @@ func TestCheckService_PatchCheck(t *testing.T) { name: "unauthorized to patch check", fields: fields{ CheckService: &mock.CheckService{ - FindCheckByIDFn: func(ctx context.Context, id influxdb.ID) (influxdb.Check, error) { + FindCheckByIDFn: func(ctx context.Context, id platform.ID) (influxdb.Check, error) { return &check.Deadman{ Base: check.Base{ ID: 1, @@ -469,7 +471,7 @@ func TestCheckService_PatchCheck(t *testing.T) { }, }, nil }, - PatchCheckFn: func(ctx context.Context, id influxdb.ID, upd influxdb.CheckUpdate) (influxdb.Check, error) { + PatchCheckFn: func(ctx context.Context, id platform.ID, upd influxdb.CheckUpdate) (influxdb.Check, error) { return &check.Deadman{ Base: check.Base{ ID: 1, @@ -492,9 +494,9 @@ func TestCheckService_PatchCheck(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/checks/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -518,7 +520,7 @@ func TestCheckService_DeleteCheck(t *testing.T) { CheckService influxdb.CheckService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -535,7 +537,7 @@ func TestCheckService_DeleteCheck(t *testing.T) { name: "authorized to delete check", fields: fields{ CheckService: &mock.CheckService{ - FindCheckByIDFn: func(ctx context.Context, id influxdb.ID) (influxdb.Check, error) { + FindCheckByIDFn: func(ctx context.Context, id platform.ID) (influxdb.Check, error) { return &check.Deadman{ Base: check.Base{ ID: 1, @@ -543,7 +545,7 @@ func TestCheckService_DeleteCheck(t *testing.T) { }, }, nil }, - DeleteCheckFn: func(ctx context.Context, id influxdb.ID) error { + DeleteCheckFn: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -575,7 +577,7 @@ func TestCheckService_DeleteCheck(t *testing.T) { name: "unauthorized to delete check", fields: fields{ CheckService: &mock.CheckService{ - FindCheckByIDFn: func(ctx context.Context, id influxdb.ID) (influxdb.Check, error) { + FindCheckByIDFn: func(ctx context.Context, id platform.ID) (influxdb.Check, error) { return &check.Deadman{ Base: check.Base{ ID: 1, @@ -583,7 +585,7 @@ func TestCheckService_DeleteCheck(t *testing.T) { }, }, nil }, - DeleteCheckFn: func(ctx context.Context, id influxdb.ID) error { + DeleteCheckFn: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -601,9 +603,9 @@ func TestCheckService_DeleteCheck(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/checks/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -628,7 +630,7 @@ func TestCheckService_CreateCheck(t *testing.T) { } type args struct { permission influxdb.Permission - orgID influxdb.ID + orgID platform.ID } type wants struct { err error @@ -644,7 +646,7 @@ func TestCheckService_CreateCheck(t *testing.T) { name: "authorized to create check with org owner", fields: fields{ CheckService: &mock.CheckService{ - CreateCheckFn: func(ctx context.Context, chk influxdb.CheckCreate, userID influxdb.ID) error { + CreateCheckFn: func(ctx context.Context, chk influxdb.CheckCreate, userID platform.ID) error { return nil }, }, @@ -667,7 +669,7 @@ func TestCheckService_CreateCheck(t *testing.T) { name: "unauthorized to create check", fields: fields{ CheckService: &mock.CheckService{ - CreateCheckFn: func(ctx context.Context, chk influxdb.CheckCreate, userID influxdb.ID) error { + CreateCheckFn: func(ctx context.Context, chk influxdb.CheckCreate, userID platform.ID) error { return nil }, }, @@ -683,9 +685,9 @@ func TestCheckService_CreateCheck(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/checks is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, diff --git a/authorizer/dashboard.go b/authorizer/dashboard.go index 2a16a6a1b95..25608bcde7c 100644 --- a/authorizer/dashboard.go +++ b/authorizer/dashboard.go @@ -3,6 +3,8 @@ package authorizer import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -22,7 +24,7 @@ func NewDashboardService(s influxdb.DashboardService) *DashboardService { } // FindDashboardByID checks to see if the authorizer on context has read access to the id provided. -func (s *DashboardService) FindDashboardByID(ctx context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { +func (s *DashboardService) FindDashboardByID(ctx context.Context, id platform.ID) (*influxdb.Dashboard, error) { b, err := s.s.FindDashboardByID(ctx, id) if err != nil { return nil, err @@ -53,7 +55,7 @@ func (s *DashboardService) CreateDashboard(ctx context.Context, b *influxdb.Dash } // UpdateDashboard checks to see if the authorizer on context has write access to the dashboard provided. -func (s *DashboardService) UpdateDashboard(ctx context.Context, id influxdb.ID, upd influxdb.DashboardUpdate) (*influxdb.Dashboard, error) { +func (s *DashboardService) UpdateDashboard(ctx context.Context, id platform.ID, upd influxdb.DashboardUpdate) (*influxdb.Dashboard, error) { b, err := s.s.FindDashboardByID(ctx, id) if err != nil { return nil, err @@ -65,7 +67,7 @@ func (s *DashboardService) UpdateDashboard(ctx context.Context, id influxdb.ID, } // DeleteDashboard checks to see if the authorizer on context has write access to the dashboard provided. -func (s *DashboardService) DeleteDashboard(ctx context.Context, id influxdb.ID) error { +func (s *DashboardService) DeleteDashboard(ctx context.Context, id platform.ID) error { b, err := s.s.FindDashboardByID(ctx, id) if err != nil { return err @@ -76,7 +78,7 @@ func (s *DashboardService) DeleteDashboard(ctx context.Context, id influxdb.ID) return s.s.DeleteDashboard(ctx, id) } -func (s *DashboardService) AddDashboardCell(ctx context.Context, id influxdb.ID, c *influxdb.Cell, opts influxdb.AddDashboardCellOptions) error { +func (s *DashboardService) AddDashboardCell(ctx context.Context, id platform.ID, c *influxdb.Cell, opts influxdb.AddDashboardCellOptions) error { b, err := s.s.FindDashboardByID(ctx, id) if err != nil { return err @@ -87,7 +89,7 @@ func (s *DashboardService) AddDashboardCell(ctx context.Context, id influxdb.ID, return s.s.AddDashboardCell(ctx, id, c, opts) } -func (s *DashboardService) RemoveDashboardCell(ctx context.Context, dashboardID influxdb.ID, cellID influxdb.ID) error { +func (s *DashboardService) RemoveDashboardCell(ctx context.Context, dashboardID platform.ID, cellID platform.ID) error { b, err := s.s.FindDashboardByID(ctx, dashboardID) if err != nil { return err @@ -98,7 +100,7 @@ func (s *DashboardService) RemoveDashboardCell(ctx context.Context, dashboardID return s.s.RemoveDashboardCell(ctx, dashboardID, cellID) } -func (s *DashboardService) UpdateDashboardCell(ctx context.Context, dashboardID influxdb.ID, cellID influxdb.ID, upd influxdb.CellUpdate) (*influxdb.Cell, error) { +func (s *DashboardService) UpdateDashboardCell(ctx context.Context, dashboardID platform.ID, cellID platform.ID, upd influxdb.CellUpdate) (*influxdb.Cell, error) { b, err := s.s.FindDashboardByID(ctx, dashboardID) if err != nil { return nil, err @@ -109,7 +111,7 @@ func (s *DashboardService) UpdateDashboardCell(ctx context.Context, dashboardID return s.s.UpdateDashboardCell(ctx, dashboardID, cellID, upd) } -func (s *DashboardService) GetDashboardCellView(ctx context.Context, dashboardID influxdb.ID, cellID influxdb.ID) (*influxdb.View, error) { +func (s *DashboardService) GetDashboardCellView(ctx context.Context, dashboardID platform.ID, cellID platform.ID) (*influxdb.View, error) { b, err := s.s.FindDashboardByID(ctx, dashboardID) if err != nil { return nil, err @@ -120,7 +122,7 @@ func (s *DashboardService) GetDashboardCellView(ctx context.Context, dashboardID return s.s.GetDashboardCellView(ctx, dashboardID, cellID) } -func (s *DashboardService) UpdateDashboardCellView(ctx context.Context, dashboardID influxdb.ID, cellID influxdb.ID, upd influxdb.ViewUpdate) (*influxdb.View, error) { +func (s *DashboardService) UpdateDashboardCellView(ctx context.Context, dashboardID platform.ID, cellID platform.ID, upd influxdb.ViewUpdate) (*influxdb.View, error) { b, err := s.s.FindDashboardByID(ctx, dashboardID) if err != nil { return nil, err @@ -131,7 +133,7 @@ func (s *DashboardService) UpdateDashboardCellView(ctx context.Context, dashboar return s.s.UpdateDashboardCellView(ctx, dashboardID, cellID, upd) } -func (s *DashboardService) ReplaceDashboardCells(ctx context.Context, id influxdb.ID, c []*influxdb.Cell) error { +func (s *DashboardService) ReplaceDashboardCells(ctx context.Context, id platform.ID, c []*influxdb.Cell) error { b, err := s.s.FindDashboardByID(ctx, id) if err != nil { return err diff --git a/authorizer/dashboard_test.go b/authorizer/dashboard_test.go index 78cbc585571..aef571fac5e 100644 --- a/authorizer/dashboard_test.go +++ b/authorizer/dashboard_test.go @@ -3,6 +3,8 @@ package authorizer_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "sort" "testing" @@ -33,7 +35,7 @@ func TestDashboardService_FindDashboardByID(t *testing.T) { } type args struct { permission influxdb.Permission - id influxdb.ID + id platform.ID } type wants struct { err error @@ -49,7 +51,7 @@ func TestDashboardService_FindDashboardByID(t *testing.T) { name: "authorized to access id", fields: fields{ DashboardService: &mock.DashboardService{ - FindDashboardByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { + FindDashboardByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Dashboard, error) { return &influxdb.Dashboard{ ID: id, OrganizationID: 10, @@ -75,7 +77,7 @@ func TestDashboardService_FindDashboardByID(t *testing.T) { name: "unauthorized to access id", fields: fields{ DashboardService: &mock.DashboardService{ - FindDashboardByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { + FindDashboardByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Dashboard, error) { return &influxdb.Dashboard{ ID: id, OrganizationID: 10, @@ -94,9 +96,9 @@ func TestDashboardService_FindDashboardByID(t *testing.T) { id: 1, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/000000000000000a/dashboards/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -249,7 +251,7 @@ func TestDashboardService_UpdateDashboard(t *testing.T) { DashboardService influxdb.DashboardService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -266,13 +268,13 @@ func TestDashboardService_UpdateDashboard(t *testing.T) { name: "authorized to update dashboard", fields: fields{ DashboardService: &mock.DashboardService{ - FindDashboardByIDF: func(ctc context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { + FindDashboardByIDF: func(ctc context.Context, id platform.ID) (*influxdb.Dashboard, error) { return &influxdb.Dashboard{ ID: 1, OrganizationID: 10, }, nil }, - UpdateDashboardF: func(ctx context.Context, id influxdb.ID, upd influxdb.DashboardUpdate) (*influxdb.Dashboard, error) { + UpdateDashboardF: func(ctx context.Context, id platform.ID, upd influxdb.DashboardUpdate) (*influxdb.Dashboard, error) { return &influxdb.Dashboard{ ID: 1, OrganizationID: 10, @@ -307,13 +309,13 @@ func TestDashboardService_UpdateDashboard(t *testing.T) { name: "unauthorized to update dashboard", fields: fields{ DashboardService: &mock.DashboardService{ - FindDashboardByIDF: func(ctc context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { + FindDashboardByIDF: func(ctc context.Context, id platform.ID) (*influxdb.Dashboard, error) { return &influxdb.Dashboard{ ID: 1, OrganizationID: 10, }, nil }, - UpdateDashboardF: func(ctx context.Context, id influxdb.ID, upd influxdb.DashboardUpdate) (*influxdb.Dashboard, error) { + UpdateDashboardF: func(ctx context.Context, id platform.ID, upd influxdb.DashboardUpdate) (*influxdb.Dashboard, error) { return &influxdb.Dashboard{ ID: 1, OrganizationID: 10, @@ -334,9 +336,9 @@ func TestDashboardService_UpdateDashboard(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/dashboards/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -360,7 +362,7 @@ func TestDashboardService_DeleteDashboard(t *testing.T) { DashboardService influxdb.DashboardService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -377,13 +379,13 @@ func TestDashboardService_DeleteDashboard(t *testing.T) { name: "authorized to delete dashboard", fields: fields{ DashboardService: &mock.DashboardService{ - FindDashboardByIDF: func(ctc context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { + FindDashboardByIDF: func(ctc context.Context, id platform.ID) (*influxdb.Dashboard, error) { return &influxdb.Dashboard{ ID: 1, OrganizationID: 10, }, nil }, - DeleteDashboardF: func(ctx context.Context, id influxdb.ID) error { + DeleteDashboardF: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -415,13 +417,13 @@ func TestDashboardService_DeleteDashboard(t *testing.T) { name: "unauthorized to delete dashboard", fields: fields{ DashboardService: &mock.DashboardService{ - FindDashboardByIDF: func(ctc context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { + FindDashboardByIDF: func(ctc context.Context, id platform.ID) (*influxdb.Dashboard, error) { return &influxdb.Dashboard{ ID: 1, OrganizationID: 10, }, nil }, - DeleteDashboardF: func(ctx context.Context, id influxdb.ID) error { + DeleteDashboardF: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -439,9 +441,9 @@ func TestDashboardService_DeleteDashboard(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/dashboards/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -466,7 +468,7 @@ func TestDashboardService_CreateDashboard(t *testing.T) { } type args struct { permission influxdb.Permission - orgID influxdb.ID + orgID platform.ID } type wants struct { err error @@ -521,9 +523,9 @@ func TestDashboardService_CreateDashboard(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/dashboards is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -548,7 +550,7 @@ func TestDashboardService_WriteDashboardCell(t *testing.T) { } type args struct { permission influxdb.Permission - orgID influxdb.ID + orgID platform.ID } type wants struct { err error @@ -564,25 +566,25 @@ func TestDashboardService_WriteDashboardCell(t *testing.T) { name: "authorized to write dashboard cells/cell/view", fields: fields{ DashboardService: &mock.DashboardService{ - FindDashboardByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { + FindDashboardByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Dashboard, error) { return &influxdb.Dashboard{ ID: id, OrganizationID: 10, }, nil }, - AddDashboardCellF: func(ctx context.Context, id influxdb.ID, c *influxdb.Cell, opts influxdb.AddDashboardCellOptions) error { + AddDashboardCellF: func(ctx context.Context, id platform.ID, c *influxdb.Cell, opts influxdb.AddDashboardCellOptions) error { return nil }, - RemoveDashboardCellF: func(ctx context.Context, id influxdb.ID, cid influxdb.ID) error { + RemoveDashboardCellF: func(ctx context.Context, id platform.ID, cid platform.ID) error { return nil }, - ReplaceDashboardCellsF: func(ctx context.Context, id influxdb.ID, cs []*influxdb.Cell) error { + ReplaceDashboardCellsF: func(ctx context.Context, id platform.ID, cs []*influxdb.Cell) error { return nil }, - UpdateDashboardCellF: func(ctx context.Context, id influxdb.ID, cid influxdb.ID, upd influxdb.CellUpdate) (*influxdb.Cell, error) { + UpdateDashboardCellF: func(ctx context.Context, id platform.ID, cid platform.ID, upd influxdb.CellUpdate) (*influxdb.Cell, error) { return &influxdb.Cell{}, nil }, - UpdateDashboardCellViewF: func(ctx context.Context, id influxdb.ID, cid influxdb.ID, upd influxdb.ViewUpdate) (*influxdb.View, error) { + UpdateDashboardCellViewF: func(ctx context.Context, id platform.ID, cid platform.ID, upd influxdb.ViewUpdate) (*influxdb.View, error) { return &influxdb.View{}, nil }, }, @@ -605,25 +607,25 @@ func TestDashboardService_WriteDashboardCell(t *testing.T) { name: "unauthorized to write dashboard cells/cell/view", fields: fields{ DashboardService: &mock.DashboardService{ - FindDashboardByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { + FindDashboardByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Dashboard, error) { return &influxdb.Dashboard{ ID: id, OrganizationID: 10, }, nil }, - AddDashboardCellF: func(ctx context.Context, id influxdb.ID, c *influxdb.Cell, opts influxdb.AddDashboardCellOptions) error { + AddDashboardCellF: func(ctx context.Context, id platform.ID, c *influxdb.Cell, opts influxdb.AddDashboardCellOptions) error { return nil }, - ReplaceDashboardCellsF: func(ctx context.Context, id influxdb.ID, cs []*influxdb.Cell) error { + ReplaceDashboardCellsF: func(ctx context.Context, id platform.ID, cs []*influxdb.Cell) error { return nil }, - UpdateDashboardCellF: func(ctx context.Context, id influxdb.ID, cid influxdb.ID, upd influxdb.CellUpdate) (*influxdb.Cell, error) { + UpdateDashboardCellF: func(ctx context.Context, id platform.ID, cid platform.ID, upd influxdb.CellUpdate) (*influxdb.Cell, error) { return &influxdb.Cell{}, nil }, - RemoveDashboardCellF: func(ctx context.Context, id influxdb.ID, cid influxdb.ID) error { + RemoveDashboardCellF: func(ctx context.Context, id platform.ID, cid platform.ID) error { return nil }, - UpdateDashboardCellViewF: func(ctx context.Context, id influxdb.ID, cid influxdb.ID, upd influxdb.ViewUpdate) (*influxdb.View, error) { + UpdateDashboardCellViewF: func(ctx context.Context, id platform.ID, cid platform.ID, upd influxdb.ViewUpdate) (*influxdb.View, error) { return &influxdb.View{}, nil }, }, @@ -639,9 +641,9 @@ func TestDashboardService_WriteDashboardCell(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/dashboards/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -678,7 +680,7 @@ func TestDashboardService_FindDashboardCellView(t *testing.T) { } type args struct { permission influxdb.Permission - orgID influxdb.ID + orgID platform.ID } type wants struct { err error @@ -694,13 +696,13 @@ func TestDashboardService_FindDashboardCellView(t *testing.T) { name: "authorized to read dashboard cells/cell/view", fields: fields{ DashboardService: &mock.DashboardService{ - FindDashboardByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { + FindDashboardByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Dashboard, error) { return &influxdb.Dashboard{ ID: id, OrganizationID: 10, }, nil }, - GetDashboardCellViewF: func(ctx context.Context, id influxdb.ID, cid influxdb.ID) (*influxdb.View, error) { + GetDashboardCellViewF: func(ctx context.Context, id platform.ID, cid platform.ID) (*influxdb.View, error) { return &influxdb.View{}, nil }, }, @@ -723,13 +725,13 @@ func TestDashboardService_FindDashboardCellView(t *testing.T) { name: "unauthorized to read dashboard cells/cell/view", fields: fields{ DashboardService: &mock.DashboardService{ - FindDashboardByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { + FindDashboardByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Dashboard, error) { return &influxdb.Dashboard{ ID: id, OrganizationID: 10, }, nil }, - GetDashboardCellViewF: func(ctx context.Context, id influxdb.ID, cid influxdb.ID) (*influxdb.View, error) { + GetDashboardCellViewF: func(ctx context.Context, id platform.ID, cid platform.ID) (*influxdb.View, error) { return &influxdb.View{}, nil }, }, @@ -745,9 +747,9 @@ func TestDashboardService_FindDashboardCellView(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/000000000000000a/dashboards/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, diff --git a/authorizer/document.go b/authorizer/document.go index 82b65463e97..49c8ad97ee3 100644 --- a/authorizer/document.go +++ b/authorizer/document.go @@ -4,6 +4,8 @@ import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -41,14 +43,14 @@ type documentStore struct { s influxdb.DocumentStore } -func newDocumentPermission(a influxdb.Action, orgID influxdb.ID, did *influxdb.ID) (*influxdb.Permission, error) { +func newDocumentPermission(a influxdb.Action, orgID platform.ID, did *platform.ID) (*influxdb.Permission, error) { if did != nil { return influxdb.NewPermissionAtID(*did, a, influxdb.DocumentsResourceType, orgID) } return influxdb.NewPermission(a, influxdb.DocumentsResourceType, orgID) } -func toPerms(action influxdb.Action, orgs map[influxdb.ID]influxdb.UserType, did *influxdb.ID) ([]influxdb.Permission, error) { +func toPerms(action influxdb.Action, orgs map[platform.ID]influxdb.UserType, did *platform.ID) ([]influxdb.Permission, error) { ps := make([]influxdb.Permission, 0, len(orgs)) for orgID := range orgs { p, err := newDocumentPermission(action, orgID, did) @@ -74,7 +76,7 @@ func (s *documentStore) CreateDocument(ctx context.Context, d *influxdb.Document return s.s.CreateDocument(ctx, d) } -func (s *documentStore) FindDocument(ctx context.Context, id influxdb.ID) (*influxdb.Document, error) { +func (s *documentStore) FindDocument(ctx context.Context, id platform.ID) (*influxdb.Document, error) { d, err := s.s.FindDocument(ctx, id) if err != nil { return nil, err @@ -89,7 +91,7 @@ func (s *documentStore) FindDocument(ctx context.Context, id influxdb.ID) (*infl return d, nil } -func (s *documentStore) FindDocuments(ctx context.Context, oid influxdb.ID) ([]*influxdb.Document, error) { +func (s *documentStore) FindDocuments(ctx context.Context, oid platform.ID) ([]*influxdb.Document, error) { if _, _, err := AuthorizeOrgReadResource(ctx, influxdb.DocumentsResourceType, oid); err != nil { return nil, err } diff --git a/authorizer/label.go b/authorizer/label.go index ec044accf62..c4ca5749426 100644 --- a/authorizer/label.go +++ b/authorizer/label.go @@ -3,6 +3,8 @@ package authorizer import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -25,7 +27,7 @@ func NewLabelServiceWithOrg(s influxdb.LabelService, orgIDResolver OrgIDResolver } // FindLabelByID checks to see if the authorizer on context has read access to the label id provided. -func (s *LabelService) FindLabelByID(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { +func (s *LabelService) FindLabelByID(ctx context.Context, id platform.ID) (*influxdb.Label, error) { l, err := s.s.FindLabelByID(ctx, id) if err != nil { return nil, err @@ -95,7 +97,7 @@ func (s *LabelService) CreateLabelMapping(ctx context.Context, m *influxdb.Label } // UpdateLabel checks to see if the authorizer on context has write access to the label provided. -func (s *LabelService) UpdateLabel(ctx context.Context, id influxdb.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { +func (s *LabelService) UpdateLabel(ctx context.Context, id platform.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { l, err := s.s.FindLabelByID(ctx, id) if err != nil { return nil, err @@ -107,7 +109,7 @@ func (s *LabelService) UpdateLabel(ctx context.Context, id influxdb.ID, upd infl } // DeleteLabel checks to see if the authorizer on context has write access to the label provided. -func (s *LabelService) DeleteLabel(ctx context.Context, id influxdb.ID) error { +func (s *LabelService) DeleteLabel(ctx context.Context, id platform.ID) error { l, err := s.s.FindLabelByID(ctx, id) if err != nil { return err diff --git a/authorizer/label_test.go b/authorizer/label_test.go index 51b71f04b59..e99db1592c9 100644 --- a/authorizer/label_test.go +++ b/authorizer/label_test.go @@ -3,6 +3,8 @@ package authorizer_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "sort" "testing" @@ -21,7 +23,7 @@ const ( var ( orgOneInfluxID = influxdbtesting.MustIDBase16(orgOneID) orgSvc = &mock.OrganizationService{ - FindResourceOrganizationIDF: func(_ context.Context, _ influxdb.ResourceType, _ influxdb.ID) (influxdb.ID, error) { + FindResourceOrganizationIDF: func(_ context.Context, _ influxdb.ResourceType, _ platform.ID) (platform.ID, error) { return orgOneInfluxID, nil }, } @@ -46,7 +48,7 @@ func TestLabelService_FindLabelByID(t *testing.T) { } type args struct { permission influxdb.Permission - id influxdb.ID + id platform.ID } type wants struct { err error @@ -62,7 +64,7 @@ func TestLabelService_FindLabelByID(t *testing.T) { name: "authorized to access id", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: id, OrgID: orgOneInfluxID, @@ -88,7 +90,7 @@ func TestLabelService_FindLabelByID(t *testing.T) { name: "unauthorized to access id", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: id, OrgID: orgOneInfluxID, @@ -107,9 +109,9 @@ func TestLabelService_FindLabelByID(t *testing.T) { id: 1, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/020f755c3c083000/labels/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -292,7 +294,7 @@ func TestLabelService_UpdateLabel(t *testing.T) { LabelService influxdb.LabelService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -309,13 +311,13 @@ func TestLabelService_UpdateLabel(t *testing.T) { name: "authorized to update label", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, }, nil }, - UpdateLabelFn: func(ctx context.Context, id influxdb.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { + UpdateLabelFn: func(ctx context.Context, id platform.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, @@ -343,13 +345,13 @@ func TestLabelService_UpdateLabel(t *testing.T) { name: "unauthorized to update label", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, }, nil }, - UpdateLabelFn: func(ctx context.Context, id influxdb.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { + UpdateLabelFn: func(ctx context.Context, id platform.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, @@ -370,9 +372,9 @@ func TestLabelService_UpdateLabel(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/020f755c3c083000/labels/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -396,7 +398,7 @@ func TestLabelService_DeleteLabel(t *testing.T) { LabelService influxdb.LabelService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -413,13 +415,13 @@ func TestLabelService_DeleteLabel(t *testing.T) { name: "authorized to delete label", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, }, nil }, - DeleteLabelFn: func(ctx context.Context, id influxdb.ID) error { + DeleteLabelFn: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -445,13 +447,13 @@ func TestLabelService_DeleteLabel(t *testing.T) { name: "unauthorized to delete label", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, }, nil }, - DeleteLabelFn: func(ctx context.Context, id influxdb.ID) error { + DeleteLabelFn: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -470,9 +472,9 @@ func TestLabelService_DeleteLabel(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/020f755c3c083000/labels/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -527,9 +529,9 @@ func TestLabelService_CreateLabel(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/020f755c3c083000/labels is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -551,9 +553,9 @@ func TestLabelService_CreateLabel(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/020f755c3c083000/labels is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -806,9 +808,9 @@ func TestLabelService_FindResourceLabels(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/020f755c3c083000/buckets/000000000000000a is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -853,7 +855,7 @@ func TestLabelService_CreateLabelMapping(t *testing.T) { name: "authorized to create label mapping", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, @@ -894,7 +896,7 @@ func TestLabelService_CreateLabelMapping(t *testing.T) { name: "unauthorized to create label mapping for resources on which the user does not have write access", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, @@ -921,8 +923,8 @@ func TestLabelService_CreateLabelMapping(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EUnauthorized, + err: &errors.Error{ + Code: errors.EUnauthorized, Msg: "write:orgs/020f755c3c083000/buckets/0000000000000002 is unauthorized", }, }, @@ -931,7 +933,7 @@ func TestLabelService_CreateLabelMapping(t *testing.T) { name: "unauthorized to create label mapping", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, @@ -958,9 +960,9 @@ func TestLabelService_CreateLabelMapping(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/020f755c3c083000/labels/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -1001,7 +1003,7 @@ func TestLabelService_DeleteLabelMapping(t *testing.T) { name: "authorized to delete label mapping", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, @@ -1042,7 +1044,7 @@ func TestLabelService_DeleteLabelMapping(t *testing.T) { name: "unauthorized to delete label mapping containing a resources on which the user does not have write access", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, @@ -1069,8 +1071,8 @@ func TestLabelService_DeleteLabelMapping(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EUnauthorized, + err: &errors.Error{ + Code: errors.EUnauthorized, Msg: "write:orgs/020f755c3c083000/buckets/0000000000000002 is unauthorized", }, }, @@ -1079,7 +1081,7 @@ func TestLabelService_DeleteLabelMapping(t *testing.T) { name: "unauthorized to delete label mapping", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, @@ -1106,9 +1108,9 @@ func TestLabelService_DeleteLabelMapping(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/020f755c3c083000/labels/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, diff --git a/authorizer/notification_endpoint.go b/authorizer/notification_endpoint.go index 856543b1c69..b8f99dbceb2 100644 --- a/authorizer/notification_endpoint.go +++ b/authorizer/notification_endpoint.go @@ -3,6 +3,9 @@ package authorizer import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) @@ -30,7 +33,7 @@ func NewNotificationEndpointService( } // FindNotificationEndpointByID checks to see if the authorizer on context has read access to the id provided. -func (s *NotificationEndpointService) FindNotificationEndpointByID(ctx context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { +func (s *NotificationEndpointService) FindNotificationEndpointByID(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { edp, err := s.s.FindNotificationEndpointByID(ctx, id) if err != nil { return nil, err @@ -45,8 +48,8 @@ func (s *NotificationEndpointService) FindNotificationEndpointByID(ctx context.C func (s *NotificationEndpointService) FindNotificationEndpoints(ctx context.Context, filter influxdb.NotificationEndpointFilter, opt ...influxdb.FindOptions) ([]influxdb.NotificationEndpoint, int, error) { // TODO: This is a temporary fix as to not fetch the entire collection when no filter is provided. if !filter.UserID.Valid() && filter.OrgID == nil { - return nil, 0, &influxdb.Error{ - Code: influxdb.EUnauthorized, + return nil, 0, &errors.Error{ + Code: errors.EUnauthorized, Msg: "cannot process a request without a org or user filter", } } @@ -61,7 +64,7 @@ func (s *NotificationEndpointService) FindNotificationEndpoints(ctx context.Cont } // CreateNotificationEndpoint checks to see if the authorizer on context has write access to the global notification endpoint resource. -func (s *NotificationEndpointService) CreateNotificationEndpoint(ctx context.Context, edp influxdb.NotificationEndpoint, userID influxdb.ID) error { +func (s *NotificationEndpointService) CreateNotificationEndpoint(ctx context.Context, edp influxdb.NotificationEndpoint, userID platform.ID) error { if _, _, err := AuthorizeCreate(ctx, influxdb.NotificationEndpointResourceType, edp.GetOrgID()); err != nil { return err } @@ -69,7 +72,7 @@ func (s *NotificationEndpointService) CreateNotificationEndpoint(ctx context.Con } // UpdateNotificationEndpoint checks to see if the authorizer on context has write access to the notification endpoint provided. -func (s *NotificationEndpointService) UpdateNotificationEndpoint(ctx context.Context, id influxdb.ID, upd influxdb.NotificationEndpoint, userID influxdb.ID) (influxdb.NotificationEndpoint, error) { +func (s *NotificationEndpointService) UpdateNotificationEndpoint(ctx context.Context, id platform.ID, upd influxdb.NotificationEndpoint, userID platform.ID) (influxdb.NotificationEndpoint, error) { edp, err := s.FindNotificationEndpointByID(ctx, id) if err != nil { return nil, err @@ -81,7 +84,7 @@ func (s *NotificationEndpointService) UpdateNotificationEndpoint(ctx context.Con } // PatchNotificationEndpoint checks to see if the authorizer on context has write access to the notification endpoint provided. -func (s *NotificationEndpointService) PatchNotificationEndpoint(ctx context.Context, id influxdb.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { +func (s *NotificationEndpointService) PatchNotificationEndpoint(ctx context.Context, id platform.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { edp, err := s.FindNotificationEndpointByID(ctx, id) if err != nil { return nil, err @@ -93,7 +96,7 @@ func (s *NotificationEndpointService) PatchNotificationEndpoint(ctx context.Cont } // DeleteNotificationEndpoint checks to see if the authorizer on context has write access to the notification endpoint provided. -func (s *NotificationEndpointService) DeleteNotificationEndpoint(ctx context.Context, id influxdb.ID) ([]influxdb.SecretField, influxdb.ID, error) { +func (s *NotificationEndpointService) DeleteNotificationEndpoint(ctx context.Context, id platform.ID) ([]influxdb.SecretField, platform.ID, error) { edp, err := s.FindNotificationEndpointByID(ctx, id) if err != nil { return nil, 0, err diff --git a/authorizer/notification_endpoint_test.go b/authorizer/notification_endpoint_test.go index 58698c7a4fa..16daf0dd901 100644 --- a/authorizer/notification_endpoint_test.go +++ b/authorizer/notification_endpoint_test.go @@ -3,6 +3,8 @@ package authorizer_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "sort" "testing" @@ -34,7 +36,7 @@ func TestNotificationEndpointService_FindNotificationEndpointByID(t *testing.T) } type args struct { permission influxdb.Permission - id influxdb.ID + id platform.ID } type wants struct { err error @@ -50,8 +52,8 @@ func TestNotificationEndpointService_FindNotificationEndpointByID(t *testing.T) name: "authorized to access id with org", fields: fields{ NotificationEndpointService: &mock.NotificationEndpointService{ - FindNotificationEndpointByIDF: func(ctx context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { - orgID := influxdb.ID(10) + FindNotificationEndpointByIDF: func(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { + orgID := platform.ID(10) return &endpoint.Slack{ Base: endpoint.Base{ ID: &id, @@ -79,8 +81,8 @@ func TestNotificationEndpointService_FindNotificationEndpointByID(t *testing.T) name: "unauthorized to access id", fields: fields{ NotificationEndpointService: &mock.NotificationEndpointService{ - FindNotificationEndpointByIDF: func(ctx context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { - orgID := influxdb.ID(10) + FindNotificationEndpointByIDF: func(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { + orgID := platform.ID(10) return &endpoint.Slack{ Base: endpoint.Base{ ID: &id, @@ -101,9 +103,9 @@ func TestNotificationEndpointService_FindNotificationEndpointByID(t *testing.T) id: 1, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/000000000000000a/notificationEndpoints/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -199,7 +201,7 @@ func TestNotificationEndpointService_FindNotificationEndpoints(t *testing.T) { ctx := context.Background() ctx = influxdbcontext.SetAuthorizer(ctx, mock.NewMockAuthorizer(false, []influxdb.Permission{tt.args.permission})) - oid := influxdb.ID(10) + oid := platform.ID(10) edps, _, err := s.FindNotificationEndpoints(ctx, influxdb.NotificationEndpointFilter{OrgID: &oid}) influxdbtesting.ErrorsEqual(t, err, tt.wants.err) @@ -215,7 +217,7 @@ func TestNotificationEndpointService_UpdateNotificationEndpoint(t *testing.T) { NotificationEndpointService influxdb.NotificationEndpointService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -232,7 +234,7 @@ func TestNotificationEndpointService_UpdateNotificationEndpoint(t *testing.T) { name: "authorized to update notificationEndpoint with org owner", fields: fields{ NotificationEndpointService: &mock.NotificationEndpointService{ - FindNotificationEndpointByIDF: func(ctc context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { + FindNotificationEndpointByIDF: func(ctc context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { return &endpoint.Slack{ Base: endpoint.Base{ ID: idPtr(1), @@ -240,7 +242,7 @@ func TestNotificationEndpointService_UpdateNotificationEndpoint(t *testing.T) { }, }, nil }, - UpdateNotificationEndpointF: func(ctx context.Context, id influxdb.ID, upd influxdb.NotificationEndpoint, userID influxdb.ID) (influxdb.NotificationEndpoint, error) { + UpdateNotificationEndpointF: func(ctx context.Context, id platform.ID, upd influxdb.NotificationEndpoint, userID platform.ID) (influxdb.NotificationEndpoint, error) { return &endpoint.Slack{ Base: endpoint.Base{ ID: idPtr(1), @@ -277,7 +279,7 @@ func TestNotificationEndpointService_UpdateNotificationEndpoint(t *testing.T) { name: "unauthorized to update notificationEndpoint", fields: fields{ NotificationEndpointService: &mock.NotificationEndpointService{ - FindNotificationEndpointByIDF: func(ctc context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { + FindNotificationEndpointByIDF: func(ctc context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { return &endpoint.Slack{ Base: endpoint.Base{ ID: idPtr(1), @@ -285,7 +287,7 @@ func TestNotificationEndpointService_UpdateNotificationEndpoint(t *testing.T) { }, }, nil }, - UpdateNotificationEndpointF: func(ctx context.Context, id influxdb.ID, upd influxdb.NotificationEndpoint, userID influxdb.ID) (influxdb.NotificationEndpoint, error) { + UpdateNotificationEndpointF: func(ctx context.Context, id platform.ID, upd influxdb.NotificationEndpoint, userID platform.ID) (influxdb.NotificationEndpoint, error) { return &endpoint.Slack{ Base: endpoint.Base{ ID: idPtr(1), @@ -308,9 +310,9 @@ func TestNotificationEndpointService_UpdateNotificationEndpoint(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/notificationEndpoints/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -325,7 +327,7 @@ func TestNotificationEndpointService_UpdateNotificationEndpoint(t *testing.T) { ctx := context.Background() ctx = influxdbcontext.SetAuthorizer(ctx, mock.NewMockAuthorizer(false, tt.args.permissions)) - _, err := s.UpdateNotificationEndpoint(ctx, tt.args.id, &endpoint.Slack{}, influxdb.ID(1)) + _, err := s.UpdateNotificationEndpoint(ctx, tt.args.id, &endpoint.Slack{}, platform.ID(1)) influxdbtesting.ErrorsEqual(t, err, tt.wants.err) }) } @@ -336,7 +338,7 @@ func TestNotificationEndpointService_PatchNotificationEndpoint(t *testing.T) { NotificationEndpointService influxdb.NotificationEndpointService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -353,7 +355,7 @@ func TestNotificationEndpointService_PatchNotificationEndpoint(t *testing.T) { name: "authorized to patch notificationEndpoint", fields: fields{ NotificationEndpointService: &mock.NotificationEndpointService{ - FindNotificationEndpointByIDF: func(ctc context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { + FindNotificationEndpointByIDF: func(ctc context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { return &endpoint.Slack{ Base: endpoint.Base{ ID: idPtr(1), @@ -361,7 +363,7 @@ func TestNotificationEndpointService_PatchNotificationEndpoint(t *testing.T) { }, }, nil }, - PatchNotificationEndpointF: func(ctx context.Context, id influxdb.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { + PatchNotificationEndpointF: func(ctx context.Context, id platform.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { return &endpoint.Slack{ Base: endpoint.Base{ ID: idPtr(1), @@ -398,7 +400,7 @@ func TestNotificationEndpointService_PatchNotificationEndpoint(t *testing.T) { name: "unauthorized to patch notificationEndpoint", fields: fields{ NotificationEndpointService: &mock.NotificationEndpointService{ - FindNotificationEndpointByIDF: func(ctc context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { + FindNotificationEndpointByIDF: func(ctc context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { return &endpoint.Slack{ Base: endpoint.Base{ ID: idPtr(1), @@ -406,7 +408,7 @@ func TestNotificationEndpointService_PatchNotificationEndpoint(t *testing.T) { }, }, nil }, - PatchNotificationEndpointF: func(ctx context.Context, id influxdb.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { + PatchNotificationEndpointF: func(ctx context.Context, id platform.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { return &endpoint.Slack{ Base: endpoint.Base{ ID: idPtr(1), @@ -429,9 +431,9 @@ func TestNotificationEndpointService_PatchNotificationEndpoint(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/notificationEndpoints/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -456,7 +458,7 @@ func TestNotificationEndpointService_DeleteNotificationEndpoint(t *testing.T) { NotificationEndpointService influxdb.NotificationEndpointService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -473,7 +475,7 @@ func TestNotificationEndpointService_DeleteNotificationEndpoint(t *testing.T) { name: "authorized to delete notificationEndpoint", fields: fields{ NotificationEndpointService: &mock.NotificationEndpointService{ - FindNotificationEndpointByIDF: func(ctc context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { + FindNotificationEndpointByIDF: func(ctc context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { return &endpoint.Slack{ Base: endpoint.Base{ ID: idPtr(1), @@ -481,7 +483,7 @@ func TestNotificationEndpointService_DeleteNotificationEndpoint(t *testing.T) { }, }, nil }, - DeleteNotificationEndpointF: func(ctx context.Context, id influxdb.ID) ([]influxdb.SecretField, influxdb.ID, error) { + DeleteNotificationEndpointF: func(ctx context.Context, id platform.ID) ([]influxdb.SecretField, platform.ID, error) { return nil, 0, nil }, }, @@ -513,7 +515,7 @@ func TestNotificationEndpointService_DeleteNotificationEndpoint(t *testing.T) { name: "unauthorized to delete notificationEndpoint", fields: fields{ NotificationEndpointService: &mock.NotificationEndpointService{ - FindNotificationEndpointByIDF: func(ctc context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { + FindNotificationEndpointByIDF: func(ctc context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { return &endpoint.Slack{ Base: endpoint.Base{ ID: idPtr(1), @@ -521,7 +523,7 @@ func TestNotificationEndpointService_DeleteNotificationEndpoint(t *testing.T) { }, }, nil }, - DeleteNotificationEndpointF: func(ctx context.Context, id influxdb.ID) ([]influxdb.SecretField, influxdb.ID, error) { + DeleteNotificationEndpointF: func(ctx context.Context, id platform.ID) ([]influxdb.SecretField, platform.ID, error) { return nil, 0, nil }, }, @@ -539,9 +541,9 @@ func TestNotificationEndpointService_DeleteNotificationEndpoint(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/notificationEndpoints/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -568,7 +570,7 @@ func TestNotificationEndpointService_CreateNotificationEndpoint(t *testing.T) { } type args struct { permission influxdb.Permission - orgID influxdb.ID + orgID platform.ID } type wants struct { err error @@ -584,7 +586,7 @@ func TestNotificationEndpointService_CreateNotificationEndpoint(t *testing.T) { name: "authorized to create notificationEndpoint", fields: fields{ NotificationEndpointService: &mock.NotificationEndpointService{ - CreateNotificationEndpointF: func(ctx context.Context, tc influxdb.NotificationEndpoint, userID influxdb.ID) error { + CreateNotificationEndpointF: func(ctx context.Context, tc influxdb.NotificationEndpoint, userID platform.ID) error { return nil }, }, @@ -607,7 +609,7 @@ func TestNotificationEndpointService_CreateNotificationEndpoint(t *testing.T) { name: "authorized to create notificationEndpoint with org owner", fields: fields{ NotificationEndpointService: &mock.NotificationEndpointService{ - CreateNotificationEndpointF: func(ctx context.Context, tc influxdb.NotificationEndpoint, userID influxdb.ID) error { + CreateNotificationEndpointF: func(ctx context.Context, tc influxdb.NotificationEndpoint, userID platform.ID) error { return nil }, }, @@ -630,7 +632,7 @@ func TestNotificationEndpointService_CreateNotificationEndpoint(t *testing.T) { name: "unauthorized to create notificationEndpoint", fields: fields{ NotificationEndpointService: &mock.NotificationEndpointService{ - CreateNotificationEndpointF: func(ctx context.Context, tc influxdb.NotificationEndpoint, userID influxdb.ID) error { + CreateNotificationEndpointF: func(ctx context.Context, tc influxdb.NotificationEndpoint, userID platform.ID) error { return nil }, }, @@ -646,9 +648,9 @@ func TestNotificationEndpointService_CreateNotificationEndpoint(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/notificationEndpoints is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -666,12 +668,12 @@ func TestNotificationEndpointService_CreateNotificationEndpoint(t *testing.T) { err := s.CreateNotificationEndpoint(ctx, &endpoint.Slack{ Base: endpoint.Base{ OrgID: idPtr(tt.args.orgID)}, - }, influxdb.ID(1)) + }, platform.ID(1)) influxdbtesting.ErrorsEqual(t, err, tt.wants.err) }) } } -func idPtr(id influxdb.ID) *influxdb.ID { +func idPtr(id platform.ID) *platform.ID { return &id } diff --git a/authorizer/notification_rule.go b/authorizer/notification_rule.go index d47cf47c7c2..4c5276ecfc4 100644 --- a/authorizer/notification_rule.go +++ b/authorizer/notification_rule.go @@ -3,6 +3,8 @@ package authorizer import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -26,7 +28,7 @@ func NewNotificationRuleStore(s influxdb.NotificationRuleStore, urm influxdb.Use } // FindNotificationRuleByID checks to see if the authorizer on context has read access to the id provided. -func (s *NotificationRuleStore) FindNotificationRuleByID(ctx context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { +func (s *NotificationRuleStore) FindNotificationRuleByID(ctx context.Context, id platform.ID) (influxdb.NotificationRule, error) { nr, err := s.s.FindNotificationRuleByID(ctx, id) if err != nil { return nil, err @@ -49,7 +51,7 @@ func (s *NotificationRuleStore) FindNotificationRules(ctx context.Context, filte } // CreateNotificationRule checks to see if the authorizer on context has write access to the global notification rule resource. -func (s *NotificationRuleStore) CreateNotificationRule(ctx context.Context, nr influxdb.NotificationRuleCreate, userID influxdb.ID) error { +func (s *NotificationRuleStore) CreateNotificationRule(ctx context.Context, nr influxdb.NotificationRuleCreate, userID platform.ID) error { if _, _, err := AuthorizeCreate(ctx, influxdb.NotificationRuleResourceType, nr.GetOrgID()); err != nil { return err } @@ -57,7 +59,7 @@ func (s *NotificationRuleStore) CreateNotificationRule(ctx context.Context, nr i } // UpdateNotificationRule checks to see if the authorizer on context has write access to the notification rule provided. -func (s *NotificationRuleStore) UpdateNotificationRule(ctx context.Context, id influxdb.ID, upd influxdb.NotificationRuleCreate, userID influxdb.ID) (influxdb.NotificationRule, error) { +func (s *NotificationRuleStore) UpdateNotificationRule(ctx context.Context, id platform.ID, upd influxdb.NotificationRuleCreate, userID platform.ID) (influxdb.NotificationRule, error) { nr, err := s.FindNotificationRuleByID(ctx, id) if err != nil { return nil, err @@ -69,7 +71,7 @@ func (s *NotificationRuleStore) UpdateNotificationRule(ctx context.Context, id i } // PatchNotificationRule checks to see if the authorizer on context has write access to the notification rule provided. -func (s *NotificationRuleStore) PatchNotificationRule(ctx context.Context, id influxdb.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { +func (s *NotificationRuleStore) PatchNotificationRule(ctx context.Context, id platform.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { nr, err := s.s.FindNotificationRuleByID(ctx, id) if err != nil { return nil, err @@ -81,7 +83,7 @@ func (s *NotificationRuleStore) PatchNotificationRule(ctx context.Context, id in } // DeleteNotificationRule checks to see if the authorizer on context has write access to the notification rule provided. -func (s *NotificationRuleStore) DeleteNotificationRule(ctx context.Context, id influxdb.ID) error { +func (s *NotificationRuleStore) DeleteNotificationRule(ctx context.Context, id platform.ID) error { nr, err := s.s.FindNotificationRuleByID(ctx, id) if err != nil { return err diff --git a/authorizer/notification_rule_test.go b/authorizer/notification_rule_test.go index a45f721b1f7..492d6b78eae 100644 --- a/authorizer/notification_rule_test.go +++ b/authorizer/notification_rule_test.go @@ -3,6 +3,8 @@ package authorizer_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "sort" "testing" @@ -34,7 +36,7 @@ func TestNotificationRuleStore_FindNotificationRuleByID(t *testing.T) { } type args struct { permission influxdb.Permission - id influxdb.ID + id platform.ID } type wants struct { err error @@ -50,7 +52,7 @@ func TestNotificationRuleStore_FindNotificationRuleByID(t *testing.T) { name: "authorized to access id", fields: fields{ NotificationRuleStore: &mock.NotificationRuleStore{ - FindNotificationRuleByIDF: func(ctx context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { + FindNotificationRuleByIDF: func(ctx context.Context, id platform.ID) (influxdb.NotificationRule, error) { return &rule.Slack{ Base: rule.Base{ ID: id, @@ -78,7 +80,7 @@ func TestNotificationRuleStore_FindNotificationRuleByID(t *testing.T) { name: "unauthorized to access id", fields: fields{ NotificationRuleStore: &mock.NotificationRuleStore{ - FindNotificationRuleByIDF: func(ctx context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { + FindNotificationRuleByIDF: func(ctx context.Context, id platform.ID) (influxdb.NotificationRule, error) { return &rule.Slack{ Base: rule.Base{ ID: id, @@ -99,9 +101,9 @@ func TestNotificationRuleStore_FindNotificationRuleByID(t *testing.T) { id: 1, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/000000000000000a/notificationRules/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -275,7 +277,7 @@ func TestNotificationRuleStore_UpdateNotificationRule(t *testing.T) { NotificationRuleStore influxdb.NotificationRuleStore } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -292,7 +294,7 @@ func TestNotificationRuleStore_UpdateNotificationRule(t *testing.T) { name: "authorized to update notificationRule", fields: fields{ NotificationRuleStore: &mock.NotificationRuleStore{ - FindNotificationRuleByIDF: func(ctc context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { + FindNotificationRuleByIDF: func(ctc context.Context, id platform.ID) (influxdb.NotificationRule, error) { return &rule.Slack{ Base: rule.Base{ ID: 1, @@ -300,7 +302,7 @@ func TestNotificationRuleStore_UpdateNotificationRule(t *testing.T) { }, }, nil }, - UpdateNotificationRuleF: func(ctx context.Context, id influxdb.ID, upd influxdb.NotificationRuleCreate, userID influxdb.ID) (influxdb.NotificationRule, error) { + UpdateNotificationRuleF: func(ctx context.Context, id platform.ID, upd influxdb.NotificationRuleCreate, userID platform.ID) (influxdb.NotificationRule, error) { return &rule.Slack{ Base: rule.Base{ ID: 1, @@ -337,7 +339,7 @@ func TestNotificationRuleStore_UpdateNotificationRule(t *testing.T) { name: "unauthorized to update notificationRule", fields: fields{ NotificationRuleStore: &mock.NotificationRuleStore{ - FindNotificationRuleByIDF: func(ctc context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { + FindNotificationRuleByIDF: func(ctc context.Context, id platform.ID) (influxdb.NotificationRule, error) { return &rule.Slack{ Base: rule.Base{ ID: 1, @@ -345,7 +347,7 @@ func TestNotificationRuleStore_UpdateNotificationRule(t *testing.T) { }, }, nil }, - UpdateNotificationRuleF: func(ctx context.Context, id influxdb.ID, upd influxdb.NotificationRuleCreate, userID influxdb.ID) (influxdb.NotificationRule, error) { + UpdateNotificationRuleF: func(ctx context.Context, id platform.ID, upd influxdb.NotificationRuleCreate, userID platform.ID) (influxdb.NotificationRule, error) { return &rule.Slack{ Base: rule.Base{ ID: 1, @@ -368,9 +370,9 @@ func TestNotificationRuleStore_UpdateNotificationRule(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/notificationRules/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -388,7 +390,7 @@ func TestNotificationRuleStore_UpdateNotificationRule(t *testing.T) { Status: influxdb.Active, } - _, err := s.UpdateNotificationRule(ctx, tt.args.id, nrc, influxdb.ID(1)) + _, err := s.UpdateNotificationRule(ctx, tt.args.id, nrc, platform.ID(1)) influxdbtesting.ErrorsEqual(t, err, tt.wants.err) }) } @@ -399,7 +401,7 @@ func TestNotificationRuleStore_PatchNotificationRule(t *testing.T) { NotificationRuleStore influxdb.NotificationRuleStore } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -416,7 +418,7 @@ func TestNotificationRuleStore_PatchNotificationRule(t *testing.T) { name: "authorized to patch notificationRule", fields: fields{ NotificationRuleStore: &mock.NotificationRuleStore{ - FindNotificationRuleByIDF: func(ctc context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { + FindNotificationRuleByIDF: func(ctc context.Context, id platform.ID) (influxdb.NotificationRule, error) { return &rule.Slack{ Base: rule.Base{ ID: 1, @@ -424,7 +426,7 @@ func TestNotificationRuleStore_PatchNotificationRule(t *testing.T) { }, }, nil }, - PatchNotificationRuleF: func(ctx context.Context, id influxdb.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { + PatchNotificationRuleF: func(ctx context.Context, id platform.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { return &rule.Slack{ Base: rule.Base{ ID: 1, @@ -461,7 +463,7 @@ func TestNotificationRuleStore_PatchNotificationRule(t *testing.T) { name: "unauthorized to patch notificationRule", fields: fields{ NotificationRuleStore: &mock.NotificationRuleStore{ - FindNotificationRuleByIDF: func(ctc context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { + FindNotificationRuleByIDF: func(ctc context.Context, id platform.ID) (influxdb.NotificationRule, error) { return &rule.Slack{ Base: rule.Base{ ID: 1, @@ -469,7 +471,7 @@ func TestNotificationRuleStore_PatchNotificationRule(t *testing.T) { }, }, nil }, - PatchNotificationRuleF: func(ctx context.Context, id influxdb.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { + PatchNotificationRuleF: func(ctx context.Context, id platform.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { return &rule.Slack{ Base: rule.Base{ ID: 1, @@ -492,9 +494,9 @@ func TestNotificationRuleStore_PatchNotificationRule(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/notificationRules/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -518,7 +520,7 @@ func TestNotificationRuleStore_DeleteNotificationRule(t *testing.T) { NotificationRuleStore influxdb.NotificationRuleStore } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -535,7 +537,7 @@ func TestNotificationRuleStore_DeleteNotificationRule(t *testing.T) { name: "authorized to delete notificationRule", fields: fields{ NotificationRuleStore: &mock.NotificationRuleStore{ - FindNotificationRuleByIDF: func(ctc context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { + FindNotificationRuleByIDF: func(ctc context.Context, id platform.ID) (influxdb.NotificationRule, error) { return &rule.Slack{ Base: rule.Base{ ID: 1, @@ -543,7 +545,7 @@ func TestNotificationRuleStore_DeleteNotificationRule(t *testing.T) { }, }, nil }, - DeleteNotificationRuleF: func(ctx context.Context, id influxdb.ID) error { + DeleteNotificationRuleF: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -575,7 +577,7 @@ func TestNotificationRuleStore_DeleteNotificationRule(t *testing.T) { name: "unauthorized to delete notificationRule", fields: fields{ NotificationRuleStore: &mock.NotificationRuleStore{ - FindNotificationRuleByIDF: func(ctc context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { + FindNotificationRuleByIDF: func(ctc context.Context, id platform.ID) (influxdb.NotificationRule, error) { return &rule.Slack{ Base: rule.Base{ ID: 1, @@ -583,7 +585,7 @@ func TestNotificationRuleStore_DeleteNotificationRule(t *testing.T) { }, }, nil }, - DeleteNotificationRuleF: func(ctx context.Context, id influxdb.ID) error { + DeleteNotificationRuleF: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -601,9 +603,9 @@ func TestNotificationRuleStore_DeleteNotificationRule(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/notificationRules/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -628,7 +630,7 @@ func TestNotificationRuleStore_CreateNotificationRule(t *testing.T) { } type args struct { permission influxdb.Permission - orgID influxdb.ID + orgID platform.ID } type wants struct { err error @@ -644,7 +646,7 @@ func TestNotificationRuleStore_CreateNotificationRule(t *testing.T) { name: "authorized to create notificationRule", fields: fields{ NotificationRuleStore: &mock.NotificationRuleStore{ - CreateNotificationRuleF: func(ctx context.Context, tc influxdb.NotificationRuleCreate, userID influxdb.ID) error { + CreateNotificationRuleF: func(ctx context.Context, tc influxdb.NotificationRuleCreate, userID platform.ID) error { return nil }, }, @@ -667,7 +669,7 @@ func TestNotificationRuleStore_CreateNotificationRule(t *testing.T) { name: "unauthorized to create notificationRule", fields: fields{ NotificationRuleStore: &mock.NotificationRuleStore{ - CreateNotificationRuleF: func(ctx context.Context, tc influxdb.NotificationRuleCreate, userID influxdb.ID) error { + CreateNotificationRuleF: func(ctx context.Context, tc influxdb.NotificationRuleCreate, userID platform.ID) error { return nil }, }, @@ -683,9 +685,9 @@ func TestNotificationRuleStore_CreateNotificationRule(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/notificationRules is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -708,7 +710,7 @@ func TestNotificationRuleStore_CreateNotificationRule(t *testing.T) { Status: influxdb.Active, } - err := s.CreateNotificationRule(ctx, nrc, influxdb.ID(1)) + err := s.CreateNotificationRule(ctx, nrc, platform.ID(1)) influxdbtesting.ErrorsEqual(t, err, tt.wants.err) }) } diff --git a/authorizer/org.go b/authorizer/org.go index 232a3bacd10..3b3726086a0 100644 --- a/authorizer/org.go +++ b/authorizer/org.go @@ -3,6 +3,8 @@ package authorizer import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" icontext "github.com/influxdata/influxdb/v2/context" ) @@ -23,7 +25,7 @@ func NewOrgService(s influxdb.OrganizationService) *OrgService { } // FindOrganizationByID checks to see if the authorizer on context has read access to the id provided. -func (s *OrgService) FindOrganizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { +func (s *OrgService) FindOrganizationByID(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { if _, _, err := AuthorizeReadOrg(ctx, id); err != nil { return nil, err } @@ -74,7 +76,7 @@ func (s *OrgService) CreateOrganization(ctx context.Context, o *influxdb.Organiz } // UpdateOrganization checks to see if the authorizer on context has write access to the organization provided. -func (s *OrgService) UpdateOrganization(ctx context.Context, id influxdb.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { +func (s *OrgService) UpdateOrganization(ctx context.Context, id platform.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { if _, _, err := AuthorizeWriteOrg(ctx, id); err != nil { return nil, err } @@ -82,7 +84,7 @@ func (s *OrgService) UpdateOrganization(ctx context.Context, id influxdb.ID, upd } // DeleteOrganization checks to see if the authorizer on context has write access to the organization provided. -func (s *OrgService) DeleteOrganization(ctx context.Context, id influxdb.ID) error { +func (s *OrgService) DeleteOrganization(ctx context.Context, id platform.ID) error { if _, _, err := AuthorizeWriteOrg(ctx, id); err != nil { return err } diff --git a/authorizer/org_test.go b/authorizer/org_test.go index 5a539825b36..6387bf50c2d 100644 --- a/authorizer/org_test.go +++ b/authorizer/org_test.go @@ -3,6 +3,8 @@ package authorizer_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "sort" "testing" @@ -33,7 +35,7 @@ func TestOrgService_FindOrganizationByID(t *testing.T) { } type args struct { permission influxdb.Permission - id influxdb.ID + id platform.ID } type wants struct { err error @@ -49,7 +51,7 @@ func TestOrgService_FindOrganizationByID(t *testing.T) { name: "authorized to access id", fields: fields{ OrgService: &mock.OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: id, }, nil @@ -74,7 +76,7 @@ func TestOrgService_FindOrganizationByID(t *testing.T) { name: "unauthorized to access id", fields: fields{ OrgService: &mock.OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: id, }, nil @@ -92,9 +94,9 @@ func TestOrgService_FindOrganizationByID(t *testing.T) { id: 1, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -174,9 +176,9 @@ func TestOrgService_FindOrganization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -314,7 +316,7 @@ func TestOrgService_UpdateOrganization(t *testing.T) { OrgService influxdb.OrganizationService } type args struct { - id influxdb.ID + id platform.ID permission influxdb.Permission } type wants struct { @@ -331,7 +333,7 @@ func TestOrgService_UpdateOrganization(t *testing.T) { name: "authorized to update org", fields: fields{ OrgService: &mock.OrganizationService{ - UpdateOrganizationF: func(ctx context.Context, id influxdb.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { + UpdateOrganizationF: func(ctx context.Context, id platform.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: 1, }, nil @@ -356,7 +358,7 @@ func TestOrgService_UpdateOrganization(t *testing.T) { name: "unauthorized to update org", fields: fields{ OrgService: &mock.OrganizationService{ - UpdateOrganizationF: func(ctx context.Context, id influxdb.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { + UpdateOrganizationF: func(ctx context.Context, id platform.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: 1, }, nil @@ -374,9 +376,9 @@ func TestOrgService_UpdateOrganization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -400,7 +402,7 @@ func TestOrgService_DeleteOrganization(t *testing.T) { OrgService influxdb.OrganizationService } type args struct { - id influxdb.ID + id platform.ID permission influxdb.Permission } type wants struct { @@ -417,7 +419,7 @@ func TestOrgService_DeleteOrganization(t *testing.T) { name: "authorized to delete org", fields: fields{ OrgService: &mock.OrganizationService{ - DeleteOrganizationF: func(ctx context.Context, id influxdb.ID) error { + DeleteOrganizationF: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -440,7 +442,7 @@ func TestOrgService_DeleteOrganization(t *testing.T) { name: "unauthorized to delete org", fields: fields{ OrgService: &mock.OrganizationService{ - DeleteOrganizationF: func(ctx context.Context, id influxdb.ID) error { + DeleteOrganizationF: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -456,9 +458,9 @@ func TestOrgService_DeleteOrganization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -534,9 +536,9 @@ func TestOrgService_CreateOrganization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, diff --git a/authorizer/password.go b/authorizer/password.go index 7d2c14daaf0..188695c343c 100644 --- a/authorizer/password.go +++ b/authorizer/password.go @@ -3,6 +3,8 @@ package authorizer import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -17,7 +19,7 @@ func NewPasswordService(svc influxdb.PasswordsService) *PasswordService { } // SetPassword overrides the password of a known user. -func (s *PasswordService) SetPassword(ctx context.Context, userID influxdb.ID, password string) error { +func (s *PasswordService) SetPassword(ctx context.Context, userID platform.ID, password string) error { if _, _, err := AuthorizeWriteResource(ctx, influxdb.UsersResourceType, userID); err != nil { return err } @@ -26,12 +28,12 @@ func (s *PasswordService) SetPassword(ctx context.Context, userID influxdb.ID, p // ComparePassword checks if the password matches the password recorded. // Passwords that do not match return errors. -func (s *PasswordService) ComparePassword(ctx context.Context, userID influxdb.ID, password string) error { +func (s *PasswordService) ComparePassword(ctx context.Context, userID platform.ID, password string) error { panic("not implemented") } // CompareAndSetPassword checks the password and if they match // updates to the new password. -func (s *PasswordService) CompareAndSetPassword(ctx context.Context, userID influxdb.ID, old string, new string) error { +func (s *PasswordService) CompareAndSetPassword(ctx context.Context, userID platform.ID, old string, new string) error { panic("not implemented") } diff --git a/authorizer/password_test.go b/authorizer/password_test.go index ac1754541eb..f203cb2cd44 100644 --- a/authorizer/password_test.go +++ b/authorizer/password_test.go @@ -2,6 +2,7 @@ package authorizer_test import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" "testing" "github.com/influxdata/influxdb/v2" @@ -14,7 +15,7 @@ import ( func TestPasswordService(t *testing.T) { t.Run("SetPassword", func(t *testing.T) { t.Run("user with permissions should proceed", func(t *testing.T) { - userID := influxdb.ID(1) + userID := platform.ID(1) permission := influxdb.Permission{ Action: influxdb.WriteAction, @@ -25,7 +26,7 @@ func TestPasswordService(t *testing.T) { } fakeSVC := mock.NewPasswordsService() - fakeSVC.SetPasswordFn = func(_ context.Context, _ influxdb.ID, _ string) error { + fakeSVC.SetPasswordFn = func(_ context.Context, _ platform.ID, _ string) error { return nil } s := authorizer.NewPasswordService(fakeSVC) @@ -37,8 +38,8 @@ func TestPasswordService(t *testing.T) { }) t.Run("user without permissions should proceed", func(t *testing.T) { - goodUserID := influxdb.ID(1) - badUserID := influxdb.ID(3) + goodUserID := platform.ID(1) + badUserID := platform.ID(3) tests := []struct { name string @@ -82,7 +83,7 @@ func TestPasswordService(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { fakeSVC := &mock.PasswordsService{ - SetPasswordFn: func(_ context.Context, _ influxdb.ID, _ string) error { + SetPasswordFn: func(_ context.Context, _ platform.ID, _ string) error { return nil }, } diff --git a/authorizer/restore.go b/authorizer/restore.go index f2fd87fa5fc..2add181c75b 100644 --- a/authorizer/restore.go +++ b/authorizer/restore.go @@ -4,6 +4,8 @@ import ( "context" "io" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/tracing" ) @@ -33,7 +35,7 @@ func (b RestoreService) RestoreKVStore(ctx context.Context, r io.Reader) error { return b.s.RestoreKVStore(ctx, r) } -func (b RestoreService) RestoreBucket(ctx context.Context, id influxdb.ID, dbi []byte) (shardIDMap map[uint64]uint64, err error) { +func (b RestoreService) RestoreBucket(ctx context.Context, id platform.ID, dbi []byte) (shardIDMap map[uint64]uint64, err error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() diff --git a/authorizer/scraper.go b/authorizer/scraper.go index 2fe424840e0..e1b65518a9c 100644 --- a/authorizer/scraper.go +++ b/authorizer/scraper.go @@ -3,6 +3,8 @@ package authorizer import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -28,7 +30,7 @@ func NewScraperTargetStoreService(s influxdb.ScraperTargetStoreService, } // GetTargetByID checks to see if the authorizer on context has read access to the id provided. -func (s *ScraperTargetStoreService) GetTargetByID(ctx context.Context, id influxdb.ID) (*influxdb.ScraperTarget, error) { +func (s *ScraperTargetStoreService) GetTargetByID(ctx context.Context, id platform.ID) (*influxdb.ScraperTarget, error) { st, err := s.s.GetTargetByID(ctx, id) if err != nil { return nil, err @@ -52,7 +54,7 @@ func (s *ScraperTargetStoreService) ListTargets(ctx context.Context, filter infl } // AddTarget checks to see if the authorizer on context has write access to the global scraper target resource. -func (s *ScraperTargetStoreService) AddTarget(ctx context.Context, st *influxdb.ScraperTarget, userID influxdb.ID) error { +func (s *ScraperTargetStoreService) AddTarget(ctx context.Context, st *influxdb.ScraperTarget, userID platform.ID) error { if _, _, err := AuthorizeCreate(ctx, influxdb.ScraperResourceType, st.OrgID); err != nil { return err } @@ -63,7 +65,7 @@ func (s *ScraperTargetStoreService) AddTarget(ctx context.Context, st *influxdb. } // UpdateTarget checks to see if the authorizer on context has write access to the scraper target provided. -func (s *ScraperTargetStoreService) UpdateTarget(ctx context.Context, upd *influxdb.ScraperTarget, userID influxdb.ID) (*influxdb.ScraperTarget, error) { +func (s *ScraperTargetStoreService) UpdateTarget(ctx context.Context, upd *influxdb.ScraperTarget, userID platform.ID) (*influxdb.ScraperTarget, error) { st, err := s.s.GetTargetByID(ctx, upd.ID) if err != nil { return nil, err @@ -78,7 +80,7 @@ func (s *ScraperTargetStoreService) UpdateTarget(ctx context.Context, upd *influ } // RemoveTarget checks to see if the authorizer on context has write access to the scraper target provided. -func (s *ScraperTargetStoreService) RemoveTarget(ctx context.Context, id influxdb.ID) error { +func (s *ScraperTargetStoreService) RemoveTarget(ctx context.Context, id platform.ID) error { st, err := s.s.GetTargetByID(ctx, id) if err != nil { return err diff --git a/authorizer/scraper_test.go b/authorizer/scraper_test.go index 7622cc76562..1ef0949b865 100644 --- a/authorizer/scraper_test.go +++ b/authorizer/scraper_test.go @@ -3,6 +3,8 @@ package authorizer_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "sort" "testing" @@ -33,7 +35,7 @@ func TestScraperTargetStoreService_GetTargetByID(t *testing.T) { } type args struct { permission influxdb.Permission - id influxdb.ID + id platform.ID } type wants struct { err error @@ -49,7 +51,7 @@ func TestScraperTargetStoreService_GetTargetByID(t *testing.T) { name: "authorized to access id", fields: fields{ ScraperTargetStoreService: &mock.ScraperTargetStoreService{ - GetTargetByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.ScraperTarget, error) { + GetTargetByIDF: func(ctx context.Context, id platform.ID) (*influxdb.ScraperTarget, error) { return &influxdb.ScraperTarget{ ID: id, OrgID: 10, @@ -75,7 +77,7 @@ func TestScraperTargetStoreService_GetTargetByID(t *testing.T) { name: "unauthorized to access id", fields: fields{ ScraperTargetStoreService: &mock.ScraperTargetStoreService{ - GetTargetByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.ScraperTarget, error) { + GetTargetByIDF: func(ctx context.Context, id platform.ID) (*influxdb.ScraperTarget, error) { return &influxdb.ScraperTarget{ ID: id, OrgID: 10, @@ -94,9 +96,9 @@ func TestScraperTargetStoreService_GetTargetByID(t *testing.T) { id: 1, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/000000000000000a/scrapers/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -249,8 +251,8 @@ func TestScraperTargetStoreService_UpdateTarget(t *testing.T) { ScraperTargetStoreService influxdb.ScraperTargetStoreService } type args struct { - id influxdb.ID - bucketID influxdb.ID + id platform.ID + bucketID platform.ID permissions []influxdb.Permission } type wants struct { @@ -267,14 +269,14 @@ func TestScraperTargetStoreService_UpdateTarget(t *testing.T) { name: "authorized to update scraper", fields: fields{ ScraperTargetStoreService: &mock.ScraperTargetStoreService{ - GetTargetByIDF: func(ctc context.Context, id influxdb.ID) (*influxdb.ScraperTarget, error) { + GetTargetByIDF: func(ctc context.Context, id platform.ID) (*influxdb.ScraperTarget, error) { return &influxdb.ScraperTarget{ ID: 1, OrgID: 10, BucketID: 100, }, nil }, - UpdateTargetF: func(ctx context.Context, upd *influxdb.ScraperTarget, userID influxdb.ID) (*influxdb.ScraperTarget, error) { + UpdateTargetF: func(ctx context.Context, upd *influxdb.ScraperTarget, userID platform.ID) (*influxdb.ScraperTarget, error) { return &influxdb.ScraperTarget{ ID: 1, OrgID: 10, @@ -318,14 +320,14 @@ func TestScraperTargetStoreService_UpdateTarget(t *testing.T) { name: "unauthorized to update scraper", fields: fields{ ScraperTargetStoreService: &mock.ScraperTargetStoreService{ - GetTargetByIDF: func(ctc context.Context, id influxdb.ID) (*influxdb.ScraperTarget, error) { + GetTargetByIDF: func(ctc context.Context, id platform.ID) (*influxdb.ScraperTarget, error) { return &influxdb.ScraperTarget{ ID: 1, OrgID: 10, BucketID: 100, }, nil }, - UpdateTargetF: func(ctx context.Context, upd *influxdb.ScraperTarget, userID influxdb.ID) (*influxdb.ScraperTarget, error) { + UpdateTargetF: func(ctx context.Context, upd *influxdb.ScraperTarget, userID platform.ID) (*influxdb.ScraperTarget, error) { return &influxdb.ScraperTarget{ ID: 1, OrgID: 10, @@ -348,9 +350,9 @@ func TestScraperTargetStoreService_UpdateTarget(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/scrapers/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -358,14 +360,14 @@ func TestScraperTargetStoreService_UpdateTarget(t *testing.T) { name: "unauthorized to write to bucket", fields: fields{ ScraperTargetStoreService: &mock.ScraperTargetStoreService{ - GetTargetByIDF: func(ctc context.Context, id influxdb.ID) (*influxdb.ScraperTarget, error) { + GetTargetByIDF: func(ctc context.Context, id platform.ID) (*influxdb.ScraperTarget, error) { return &influxdb.ScraperTarget{ ID: 1, OrgID: 10, BucketID: 100, }, nil }, - UpdateTargetF: func(ctx context.Context, upd *influxdb.ScraperTarget, userID influxdb.ID) (*influxdb.ScraperTarget, error) { + UpdateTargetF: func(ctx context.Context, upd *influxdb.ScraperTarget, userID platform.ID) (*influxdb.ScraperTarget, error) { return &influxdb.ScraperTarget{ ID: 1, OrgID: 10, @@ -388,9 +390,9 @@ func TestScraperTargetStoreService_UpdateTarget(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/buckets/0000000000000064 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -404,7 +406,7 @@ func TestScraperTargetStoreService_UpdateTarget(t *testing.T) { ctx := context.Background() ctx = influxdbcontext.SetAuthorizer(ctx, mock.NewMockAuthorizer(false, tt.args.permissions)) - _, err := s.UpdateTarget(ctx, &influxdb.ScraperTarget{ID: tt.args.id, BucketID: tt.args.bucketID}, influxdb.ID(1)) + _, err := s.UpdateTarget(ctx, &influxdb.ScraperTarget{ID: tt.args.id, BucketID: tt.args.bucketID}, platform.ID(1)) influxdbtesting.ErrorsEqual(t, err, tt.wants.err) }) } @@ -415,7 +417,7 @@ func TestScraperTargetStoreService_RemoveTarget(t *testing.T) { ScraperTargetStoreService influxdb.ScraperTargetStoreService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -432,13 +434,13 @@ func TestScraperTargetStoreService_RemoveTarget(t *testing.T) { name: "authorized to delete scraper", fields: fields{ ScraperTargetStoreService: &mock.ScraperTargetStoreService{ - GetTargetByIDF: func(ctc context.Context, id influxdb.ID) (*influxdb.ScraperTarget, error) { + GetTargetByIDF: func(ctc context.Context, id platform.ID) (*influxdb.ScraperTarget, error) { return &influxdb.ScraperTarget{ ID: 1, OrgID: 10, }, nil }, - RemoveTargetF: func(ctx context.Context, id influxdb.ID) error { + RemoveTargetF: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -470,13 +472,13 @@ func TestScraperTargetStoreService_RemoveTarget(t *testing.T) { name: "unauthorized to delete scraper", fields: fields{ ScraperTargetStoreService: &mock.ScraperTargetStoreService{ - GetTargetByIDF: func(ctc context.Context, id influxdb.ID) (*influxdb.ScraperTarget, error) { + GetTargetByIDF: func(ctc context.Context, id platform.ID) (*influxdb.ScraperTarget, error) { return &influxdb.ScraperTarget{ ID: 1, OrgID: 10, }, nil }, - RemoveTargetF: func(ctx context.Context, id influxdb.ID) error { + RemoveTargetF: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -494,9 +496,9 @@ func TestScraperTargetStoreService_RemoveTarget(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/scrapers/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -522,8 +524,8 @@ func TestScraperTargetStoreService_AddTarget(t *testing.T) { } type args struct { permissions []influxdb.Permission - orgID influxdb.ID - bucketID influxdb.ID + orgID platform.ID + bucketID platform.ID } type wants struct { err error @@ -539,7 +541,7 @@ func TestScraperTargetStoreService_AddTarget(t *testing.T) { name: "authorized to create scraper", fields: fields{ ScraperTargetStoreService: &mock.ScraperTargetStoreService{ - AddTargetF: func(ctx context.Context, st *influxdb.ScraperTarget, userID influxdb.ID) error { + AddTargetF: func(ctx context.Context, st *influxdb.ScraperTarget, userID platform.ID) error { return nil }, }, @@ -572,7 +574,7 @@ func TestScraperTargetStoreService_AddTarget(t *testing.T) { name: "unauthorized to create scraper", fields: fields{ ScraperTargetStoreService: &mock.ScraperTargetStoreService{ - AddTargetF: func(ctx context.Context, st *influxdb.ScraperTarget, userID influxdb.ID) error { + AddTargetF: func(ctx context.Context, st *influxdb.ScraperTarget, userID platform.ID) error { return nil }, }, @@ -598,9 +600,9 @@ func TestScraperTargetStoreService_AddTarget(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/scrapers is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -608,7 +610,7 @@ func TestScraperTargetStoreService_AddTarget(t *testing.T) { name: "unauthorized to write to bucket", fields: fields{ ScraperTargetStoreService: &mock.ScraperTargetStoreService{ - AddTargetF: func(ctx context.Context, st *influxdb.ScraperTarget, userID influxdb.ID) error { + AddTargetF: func(ctx context.Context, st *influxdb.ScraperTarget, userID platform.ID) error { return nil }, }, @@ -634,9 +636,9 @@ func TestScraperTargetStoreService_AddTarget(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/buckets/0000000000000064 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -650,7 +652,7 @@ func TestScraperTargetStoreService_AddTarget(t *testing.T) { ctx := context.Background() ctx = influxdbcontext.SetAuthorizer(ctx, mock.NewMockAuthorizer(false, tt.args.permissions)) - err := s.AddTarget(ctx, &influxdb.ScraperTarget{OrgID: tt.args.orgID, BucketID: tt.args.bucketID}, influxdb.ID(1)) + err := s.AddTarget(ctx, &influxdb.ScraperTarget{OrgID: tt.args.orgID, BucketID: tt.args.bucketID}, platform.ID(1)) influxdbtesting.ErrorsEqual(t, err, tt.wants.err) }) } diff --git a/authorizer/secret.go b/authorizer/secret.go index baefe02465c..f0fe2bba9dc 100644 --- a/authorizer/secret.go +++ b/authorizer/secret.go @@ -3,6 +3,8 @@ package authorizer import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -22,7 +24,7 @@ func NewSecretService(s influxdb.SecretService) *SecretService { } // LoadSecret checks to see if the authorizer on context has read access to the secret key provided. -func (s *SecretService) LoadSecret(ctx context.Context, orgID influxdb.ID, key string) (string, error) { +func (s *SecretService) LoadSecret(ctx context.Context, orgID platform.ID, key string) (string, error) { if _, _, err := AuthorizeOrgReadResource(ctx, influxdb.SecretsResourceType, orgID); err != nil { return "", err } @@ -34,7 +36,7 @@ func (s *SecretService) LoadSecret(ctx context.Context, orgID influxdb.ID, key s } // GetSecretKeys checks to see if the authorizer on context has read access to all the secrets belonging to orgID. -func (s *SecretService) GetSecretKeys(ctx context.Context, orgID influxdb.ID) ([]string, error) { +func (s *SecretService) GetSecretKeys(ctx context.Context, orgID platform.ID) ([]string, error) { if _, _, err := AuthorizeOrgReadResource(ctx, influxdb.SecretsResourceType, orgID); err != nil { return []string{}, err } @@ -46,7 +48,7 @@ func (s *SecretService) GetSecretKeys(ctx context.Context, orgID influxdb.ID) ([ } // PutSecret checks to see if the authorizer on context has write access to the secret key provided. -func (s *SecretService) PutSecret(ctx context.Context, orgID influxdb.ID, key string, val string) error { +func (s *SecretService) PutSecret(ctx context.Context, orgID platform.ID, key string, val string) error { if _, _, err := AuthorizeCreate(ctx, influxdb.SecretsResourceType, orgID); err != nil { return err } @@ -58,7 +60,7 @@ func (s *SecretService) PutSecret(ctx context.Context, orgID influxdb.ID, key st } // PutSecrets checks to see if the authorizer on context has read and write access to the secret keys provided. -func (s *SecretService) PutSecrets(ctx context.Context, orgID influxdb.ID, m map[string]string) error { +func (s *SecretService) PutSecrets(ctx context.Context, orgID platform.ID, m map[string]string) error { // PutSecrets operates on intersection between m and keys beloging to orgID. // We need to have read access to those secrets since it deletes the secrets (within the intersection) that have not be overridden. if _, _, err := AuthorizeOrgReadResource(ctx, influxdb.SecretsResourceType, orgID); err != nil { @@ -75,7 +77,7 @@ func (s *SecretService) PutSecrets(ctx context.Context, orgID influxdb.ID, m map } // PatchSecrets checks to see if the authorizer on context has write access to the secret keys provided. -func (s *SecretService) PatchSecrets(ctx context.Context, orgID influxdb.ID, m map[string]string) error { +func (s *SecretService) PatchSecrets(ctx context.Context, orgID platform.ID, m map[string]string) error { if _, _, err := AuthorizeOrgWriteResource(ctx, influxdb.SecretsResourceType, orgID); err != nil { return err } @@ -87,7 +89,7 @@ func (s *SecretService) PatchSecrets(ctx context.Context, orgID influxdb.ID, m m } // DeleteSecret checks to see if the authorizer on context has write access to the secret keys provided. -func (s *SecretService) DeleteSecret(ctx context.Context, orgID influxdb.ID, keys ...string) error { +func (s *SecretService) DeleteSecret(ctx context.Context, orgID platform.ID, keys ...string) error { if _, _, err := AuthorizeOrgWriteResource(ctx, influxdb.SecretsResourceType, orgID); err != nil { return err } diff --git a/authorizer/secret_test.go b/authorizer/secret_test.go index 34c7664e882..61271170b0d 100644 --- a/authorizer/secret_test.go +++ b/authorizer/secret_test.go @@ -3,6 +3,8 @@ package authorizer_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "testing" "github.com/google/go-cmp/cmp" @@ -25,7 +27,7 @@ func TestSecretService_LoadSecret(t *testing.T) { } type args struct { permission influxdb.Permission - org influxdb.ID + org platform.ID key string } type wants struct { @@ -42,12 +44,12 @@ func TestSecretService_LoadSecret(t *testing.T) { name: "authorized to access secret within org", fields: fields{ SecretService: &mock.SecretService{ - LoadSecretFn: func(ctx context.Context, orgID influxdb.ID, k string) (string, error) { + LoadSecretFn: func(ctx context.Context, orgID platform.ID, k string) (string, error) { if k == "key" { return "val", nil } - return "", &influxdb.Error{ - Code: influxdb.ENotFound, + return "", &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrSecretNotFound, } }, @@ -62,7 +64,7 @@ func TestSecretService_LoadSecret(t *testing.T) { }, }, key: "key", - org: influxdb.ID(10), + org: platform.ID(10), }, wants: wants{ err: nil, @@ -72,12 +74,12 @@ func TestSecretService_LoadSecret(t *testing.T) { name: "cannot access not existing secret", fields: fields{ SecretService: &mock.SecretService{ - LoadSecretFn: func(ctx context.Context, orgID influxdb.ID, k string) (string, error) { + LoadSecretFn: func(ctx context.Context, orgID platform.ID, k string) (string, error) { if k == "key" { return "val", nil } - return "", &influxdb.Error{ - Code: influxdb.ENotFound, + return "", &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrSecretNotFound, } }, @@ -92,11 +94,11 @@ func TestSecretService_LoadSecret(t *testing.T) { }, }, key: "not existing", - org: influxdb.ID(10), + org: platform.ID(10), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrSecretNotFound, }, }, @@ -105,12 +107,12 @@ func TestSecretService_LoadSecret(t *testing.T) { name: "unauthorized to access secret within org", fields: fields{ SecretService: &mock.SecretService{ - LoadSecretFn: func(ctx context.Context, orgID influxdb.ID, k string) (string, error) { + LoadSecretFn: func(ctx context.Context, orgID platform.ID, k string) (string, error) { if k == "key" { return "val", nil } - return "", &influxdb.Error{ - Code: influxdb.ENotFound, + return "", &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrSecretNotFound, } }, @@ -124,13 +126,13 @@ func TestSecretService_LoadSecret(t *testing.T) { ID: influxdbtesting.IDPtr(10), }, }, - org: influxdb.ID(2), + org: platform.ID(2), key: "key", }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/0000000000000002/secrets is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -155,7 +157,7 @@ func TestSecretService_GetSecretKeys(t *testing.T) { } type args struct { permission influxdb.Permission - org influxdb.ID + org platform.ID } type wants struct { err error @@ -172,7 +174,7 @@ func TestSecretService_GetSecretKeys(t *testing.T) { name: "authorized to see all secrets within an org", fields: fields{ SecretService: &mock.SecretService{ - GetSecretKeysFn: func(ctx context.Context, orgID influxdb.ID) ([]string, error) { + GetSecretKeysFn: func(ctx context.Context, orgID platform.ID) ([]string, error) { return []string{ "0000000000000001secret1", "0000000000000001secret2", @@ -189,7 +191,7 @@ func TestSecretService_GetSecretKeys(t *testing.T) { OrgID: influxdbtesting.IDPtr(1), }, }, - org: influxdb.ID(1), + org: platform.ID(1), }, wants: wants{ secrets: []string{ @@ -203,7 +205,7 @@ func TestSecretService_GetSecretKeys(t *testing.T) { name: "unauthorized to see all secrets within an org", fields: fields{ SecretService: &mock.SecretService{ - GetSecretKeysFn: func(ctx context.Context, orgID influxdb.ID) ([]string, error) { + GetSecretKeysFn: func(ctx context.Context, orgID platform.ID) ([]string, error) { return []string{ "0000000000000002secret1", "0000000000000002secret2", @@ -220,11 +222,11 @@ func TestSecretService_GetSecretKeys(t *testing.T) { OrgID: influxdbtesting.IDPtr(1), }, }, - org: influxdb.ID(2), + org: platform.ID(2), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EUnauthorized, + err: &errors.Error{ + Code: errors.EUnauthorized, Msg: "read:orgs/0000000000000002/secrets is unauthorized", }, secrets: []string{}, @@ -234,9 +236,9 @@ func TestSecretService_GetSecretKeys(t *testing.T) { name: "errors when there are not secret into an org", fields: fields{ SecretService: &mock.SecretService{ - GetSecretKeysFn: func(ctx context.Context, orgID influxdb.ID) ([]string, error) { - return []string(nil), &influxdb.Error{ - Code: influxdb.ENotFound, + GetSecretKeysFn: func(ctx context.Context, orgID platform.ID) ([]string, error) { + return []string(nil), &errors.Error{ + Code: errors.ENotFound, Msg: "organization has no secret keys", } }, @@ -250,11 +252,11 @@ func TestSecretService_GetSecretKeys(t *testing.T) { OrgID: influxdbtesting.IDPtr(10), }, }, - org: influxdb.ID(10), + org: platform.ID(10), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "organization has no secret keys", }, secrets: []string{}, @@ -284,7 +286,7 @@ func TestSecretService_PatchSecrets(t *testing.T) { SecretService influxdb.SecretService } type args struct { - org influxdb.ID + org platform.ID permissions []influxdb.Permission } type wants struct { @@ -301,13 +303,13 @@ func TestSecretService_PatchSecrets(t *testing.T) { name: "authorized to patch secrets", fields: fields{ SecretService: &mock.SecretService{ - PatchSecretsFn: func(ctx context.Context, orgID influxdb.ID, m map[string]string) error { + PatchSecretsFn: func(ctx context.Context, orgID platform.ID, m map[string]string) error { return nil }, }, }, args: args{ - org: influxdb.ID(1), + org: platform.ID(1), permissions: []influxdb.Permission{ { Action: influxdb.WriteAction, @@ -326,13 +328,13 @@ func TestSecretService_PatchSecrets(t *testing.T) { name: "unauthorized to update secret", fields: fields{ SecretService: &mock.SecretService{ - PatchSecretsFn: func(ctx context.Context, orgID influxdb.ID, m map[string]string) error { + PatchSecretsFn: func(ctx context.Context, orgID platform.ID, m map[string]string) error { return nil }, }, }, args: args{ - org: influxdb.ID(1), + org: platform.ID(1), permissions: []influxdb.Permission{ { Action: influxdb.ReadAction, @@ -344,9 +346,9 @@ func TestSecretService_PatchSecrets(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/0000000000000001/secrets is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -371,7 +373,7 @@ func TestSecretService_DeleteSecret(t *testing.T) { SecretService influxdb.SecretService } type args struct { - org influxdb.ID + org platform.ID permissions []influxdb.Permission } type wants struct { @@ -388,13 +390,13 @@ func TestSecretService_DeleteSecret(t *testing.T) { name: "authorized to delete secret", fields: fields{ SecretService: &mock.SecretService{ - DeleteSecretFn: func(ctx context.Context, orgID influxdb.ID, keys ...string) error { + DeleteSecretFn: func(ctx context.Context, orgID platform.ID, keys ...string) error { return nil }, }, }, args: args{ - org: influxdb.ID(1), + org: platform.ID(1), permissions: []influxdb.Permission{ { Action: influxdb.WriteAction, @@ -413,7 +415,7 @@ func TestSecretService_DeleteSecret(t *testing.T) { name: "unauthorized to delete secret", fields: fields{ SecretService: &mock.SecretService{ - DeleteSecretFn: func(ctx context.Context, orgID influxdb.ID, keys ...string) error { + DeleteSecretFn: func(ctx context.Context, orgID platform.ID, keys ...string) error { return nil }, }, @@ -431,9 +433,9 @@ func TestSecretService_DeleteSecret(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/secrets is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -458,7 +460,7 @@ func TestSecretService_PutSecret(t *testing.T) { } type args struct { permission influxdb.Permission - orgID influxdb.ID + orgID platform.ID } type wants struct { err error @@ -474,13 +476,13 @@ func TestSecretService_PutSecret(t *testing.T) { name: "authorized to put a secret", fields: fields{ SecretService: &mock.SecretService{ - PutSecretFn: func(ctx context.Context, orgID influxdb.ID, key string, val string) error { + PutSecretFn: func(ctx context.Context, orgID platform.ID, key string, val string) error { return nil }, }, }, args: args{ - orgID: influxdb.ID(10), + orgID: platform.ID(10), permission: influxdb.Permission{ Action: influxdb.WriteAction, Resource: influxdb.Resource{ @@ -497,7 +499,7 @@ func TestSecretService_PutSecret(t *testing.T) { name: "unauthorized to put a secret", fields: fields{ SecretService: &mock.SecretService{ - PutSecretFn: func(ctx context.Context, orgID influxdb.ID, key string, val string) error { + PutSecretFn: func(ctx context.Context, orgID platform.ID, key string, val string) error { return nil }, }, @@ -513,9 +515,9 @@ func TestSecretService_PutSecret(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/secrets is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -540,7 +542,7 @@ func TestSecretService_PutSecrets(t *testing.T) { } type args struct { permissions []influxdb.Permission - orgID influxdb.ID + orgID platform.ID } type wants struct { err error @@ -556,13 +558,13 @@ func TestSecretService_PutSecrets(t *testing.T) { name: "authorized to put secrets", fields: fields{ SecretService: &mock.SecretService{ - PutSecretsFn: func(ctx context.Context, orgID influxdb.ID, m map[string]string) error { + PutSecretsFn: func(ctx context.Context, orgID platform.ID, m map[string]string) error { return nil }, }, }, args: args{ - orgID: influxdb.ID(10), + orgID: platform.ID(10), permissions: []influxdb.Permission{ { Action: influxdb.WriteAction, @@ -588,13 +590,13 @@ func TestSecretService_PutSecrets(t *testing.T) { name: "unauthorized to put secrets", fields: fields{ SecretService: &mock.SecretService{ - PutSecretsFn: func(ctx context.Context, orgID influxdb.ID, m map[string]string) error { + PutSecretsFn: func(ctx context.Context, orgID platform.ID, m map[string]string) error { return nil }, }, }, args: args{ - orgID: influxdb.ID(2), + orgID: platform.ID(2), permissions: []influxdb.Permission{ { Action: influxdb.WriteAction, @@ -613,9 +615,9 @@ func TestSecretService_PutSecrets(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/0000000000000002/secrets is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -623,10 +625,10 @@ func TestSecretService_PutSecrets(t *testing.T) { name: "unauthorized to put secrets without read access to their org", fields: fields{ SecretService: &mock.SecretService{ - PutSecretFn: func(ctx context.Context, orgID influxdb.ID, key string, val string) error { + PutSecretFn: func(ctx context.Context, orgID platform.ID, key string, val string) error { return nil }, - PutSecretsFn: func(ctx context.Context, orgID influxdb.ID, m map[string]string) error { + PutSecretsFn: func(ctx context.Context, orgID platform.ID, m map[string]string) error { return nil }, }, @@ -644,9 +646,9 @@ func TestSecretService_PutSecrets(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/000000000000000a/secrets is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -654,10 +656,10 @@ func TestSecretService_PutSecrets(t *testing.T) { name: "unauthorized to put secrets without write access to their org", fields: fields{ SecretService: &mock.SecretService{ - PutSecretFn: func(ctx context.Context, orgID influxdb.ID, key string, val string) error { + PutSecretFn: func(ctx context.Context, orgID platform.ID, key string, val string) error { return nil }, - PutSecretsFn: func(ctx context.Context, orgID influxdb.ID, m map[string]string) error { + PutSecretsFn: func(ctx context.Context, orgID platform.ID, m map[string]string) error { return nil }, }, @@ -675,9 +677,9 @@ func TestSecretService_PutSecrets(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/secrets is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, diff --git a/authorizer/source.go b/authorizer/source.go index ff5fa1ab249..5dc170347ed 100644 --- a/authorizer/source.go +++ b/authorizer/source.go @@ -3,6 +3,8 @@ package authorizer import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -34,7 +36,7 @@ func (s *SourceService) DefaultSource(ctx context.Context) (*influxdb.Source, er } // FindSourceByID checks to see if the authorizer on context has read access to the id provided. -func (s *SourceService) FindSourceByID(ctx context.Context, id influxdb.ID) (*influxdb.Source, error) { +func (s *SourceService) FindSourceByID(ctx context.Context, id platform.ID) (*influxdb.Source, error) { src, err := s.s.FindSourceByID(ctx, id) if err != nil { return nil, err @@ -64,7 +66,7 @@ func (s *SourceService) CreateSource(ctx context.Context, src *influxdb.Source) } // UpdateSource checks to see if the authorizer on context has write access to the source provided. -func (s *SourceService) UpdateSource(ctx context.Context, id influxdb.ID, upd influxdb.SourceUpdate) (*influxdb.Source, error) { +func (s *SourceService) UpdateSource(ctx context.Context, id platform.ID, upd influxdb.SourceUpdate) (*influxdb.Source, error) { src, err := s.s.FindSourceByID(ctx, id) if err != nil { return nil, err @@ -76,7 +78,7 @@ func (s *SourceService) UpdateSource(ctx context.Context, id influxdb.ID, upd in } // DeleteSource checks to see if the authorizer on context has write access to the source provided. -func (s *SourceService) DeleteSource(ctx context.Context, id influxdb.ID) error { +func (s *SourceService) DeleteSource(ctx context.Context, id platform.ID) error { src, err := s.s.FindSourceByID(ctx, id) if err != nil { return err diff --git a/authorizer/source_test.go b/authorizer/source_test.go index 1cecbfbca3f..69be29dd04d 100644 --- a/authorizer/source_test.go +++ b/authorizer/source_test.go @@ -3,6 +3,8 @@ package authorizer_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "sort" "testing" @@ -91,9 +93,9 @@ func TestSourceService_DefaultSource(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/000000000000000a/sources/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -118,7 +120,7 @@ func TestSourceService_FindSourceByID(t *testing.T) { } type args struct { permission influxdb.Permission - id influxdb.ID + id platform.ID } type wants struct { err error @@ -134,7 +136,7 @@ func TestSourceService_FindSourceByID(t *testing.T) { name: "authorized to access id", fields: fields{ SourceService: &mock.SourceService{ - FindSourceByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Source, error) { + FindSourceByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Source, error) { return &influxdb.Source{ ID: id, OrganizationID: 10, @@ -160,7 +162,7 @@ func TestSourceService_FindSourceByID(t *testing.T) { name: "unauthorized to access id", fields: fields{ SourceService: &mock.SourceService{ - FindSourceByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Source, error) { + FindSourceByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Source, error) { return &influxdb.Source{ ID: id, OrganizationID: 10, @@ -179,9 +181,9 @@ func TestSourceService_FindSourceByID(t *testing.T) { id: 1, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/000000000000000a/sources/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -333,7 +335,7 @@ func TestSourceService_UpdateSource(t *testing.T) { SourceService influxdb.SourceService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -350,13 +352,13 @@ func TestSourceService_UpdateSource(t *testing.T) { name: "authorized to update source", fields: fields{ SourceService: &mock.SourceService{ - FindSourceByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Source, error) { + FindSourceByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Source, error) { return &influxdb.Source{ ID: 1, OrganizationID: 10, }, nil }, - UpdateSourceFn: func(ctx context.Context, id influxdb.ID, upd influxdb.SourceUpdate) (*influxdb.Source, error) { + UpdateSourceFn: func(ctx context.Context, id platform.ID, upd influxdb.SourceUpdate) (*influxdb.Source, error) { return &influxdb.Source{ ID: 1, OrganizationID: 10, @@ -391,13 +393,13 @@ func TestSourceService_UpdateSource(t *testing.T) { name: "unauthorized to update source", fields: fields{ SourceService: &mock.SourceService{ - FindSourceByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Source, error) { + FindSourceByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Source, error) { return &influxdb.Source{ ID: 1, OrganizationID: 10, }, nil }, - UpdateSourceFn: func(ctx context.Context, id influxdb.ID, upd influxdb.SourceUpdate) (*influxdb.Source, error) { + UpdateSourceFn: func(ctx context.Context, id platform.ID, upd influxdb.SourceUpdate) (*influxdb.Source, error) { return &influxdb.Source{ ID: 1, OrganizationID: 10, @@ -418,9 +420,9 @@ func TestSourceService_UpdateSource(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/sources/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -444,7 +446,7 @@ func TestSourceService_DeleteSource(t *testing.T) { SourceService influxdb.SourceService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -461,13 +463,13 @@ func TestSourceService_DeleteSource(t *testing.T) { name: "authorized to delete source", fields: fields{ SourceService: &mock.SourceService{ - FindSourceByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Source, error) { + FindSourceByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Source, error) { return &influxdb.Source{ ID: 1, OrganizationID: 10, }, nil }, - DeleteSourceFn: func(ctx context.Context, id influxdb.ID) error { + DeleteSourceFn: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -499,13 +501,13 @@ func TestSourceService_DeleteSource(t *testing.T) { name: "unauthorized to delete source", fields: fields{ SourceService: &mock.SourceService{ - FindSourceByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Source, error) { + FindSourceByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Source, error) { return &influxdb.Source{ ID: 1, OrganizationID: 10, }, nil }, - DeleteSourceFn: func(ctx context.Context, id influxdb.ID) error { + DeleteSourceFn: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -523,9 +525,9 @@ func TestSourceService_DeleteSource(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/sources/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -550,7 +552,7 @@ func TestSourceService_CreateSource(t *testing.T) { } type args struct { permission influxdb.Permission - orgID influxdb.ID + orgID platform.ID } type wants struct { err error @@ -605,9 +607,9 @@ func TestSourceService_CreateSource(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/sources is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, diff --git a/authorizer/task.go b/authorizer/task.go index 9303d1b8cfe..685cf45f610 100644 --- a/authorizer/task.go +++ b/authorizer/task.go @@ -4,6 +4,9 @@ import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/tracing" "go.uber.org/zap" @@ -20,13 +23,13 @@ func (ae *authError) AuthzError() error { } var ( - ErrInactiveTask = &influxdb.Error{ - Code: influxdb.EInvalid, + ErrInactiveTask = &errors.Error{ + Code: errors.EInvalid, Msg: "inactive task", } - ErrFailedPermission = &influxdb.Error{ - Code: influxdb.EInvalid, + ErrFailedPermission = &errors.Error{ + Code: errors.EInvalid, Msg: "unauthorized", } ) @@ -46,7 +49,7 @@ func NewTaskService(log *zap.Logger, ts influxdb.TaskService) influxdb.TaskServi } func (ts *taskServiceValidator) processPermissionError(a influxdb.Authorizer, p influxdb.Permission, err error, loggerFields ...zap.Field) error { - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors.ErrorCode(err) == errors.EUnauthorized { ts.log.With(loggerFields...).Info("Authorization failed", zap.String("user_id", a.GetUserID().String()), zap.String("auth_kind", a.Kind()), @@ -58,7 +61,7 @@ func (ts *taskServiceValidator) processPermissionError(a influxdb.Authorizer, p return err } -func (ts *taskServiceValidator) FindTaskByID(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { +func (ts *taskServiceValidator) FindTaskByID(ctx context.Context, id platform.ID) (*influxdb.Task, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -103,7 +106,7 @@ func (ts *taskServiceValidator) CreateTask(ctx context.Context, t influxdb.TaskC return ts.TaskService.CreateTask(ctx, t) } -func (ts *taskServiceValidator) UpdateTask(ctx context.Context, id influxdb.ID, upd influxdb.TaskUpdate) (*influxdb.Task, error) { +func (ts *taskServiceValidator) UpdateTask(ctx context.Context, id platform.ID, upd influxdb.TaskUpdate) (*influxdb.Task, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -121,7 +124,7 @@ func (ts *taskServiceValidator) UpdateTask(ctx context.Context, id influxdb.ID, return ts.TaskService.UpdateTask(ctx, id, upd) } -func (ts *taskServiceValidator) DeleteTask(ctx context.Context, id influxdb.ID) error { +func (ts *taskServiceValidator) DeleteTask(ctx context.Context, id platform.ID) error { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -171,7 +174,7 @@ func (ts *taskServiceValidator) FindRuns(ctx context.Context, filter influxdb.Ru return ts.TaskService.FindRuns(ctx, filter) } -func (ts *taskServiceValidator) FindRunByID(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (ts *taskServiceValidator) FindRunByID(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -189,7 +192,7 @@ func (ts *taskServiceValidator) FindRunByID(ctx context.Context, taskID, runID i return ts.TaskService.FindRunByID(ctx, taskID, runID) } -func (ts *taskServiceValidator) CancelRun(ctx context.Context, taskID, runID influxdb.ID) error { +func (ts *taskServiceValidator) CancelRun(ctx context.Context, taskID, runID platform.ID) error { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -207,7 +210,7 @@ func (ts *taskServiceValidator) CancelRun(ctx context.Context, taskID, runID inf return ts.TaskService.CancelRun(ctx, taskID, runID) } -func (ts *taskServiceValidator) RetryRun(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (ts *taskServiceValidator) RetryRun(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -229,7 +232,7 @@ func (ts *taskServiceValidator) RetryRun(ctx context.Context, taskID, runID infl return ts.TaskService.RetryRun(ctx, taskID, runID) } -func (ts *taskServiceValidator) ForceRun(ctx context.Context, taskID influxdb.ID, scheduledFor int64) (*influxdb.Run, error) { +func (ts *taskServiceValidator) ForceRun(ctx context.Context, taskID platform.ID, scheduledFor int64) (*influxdb.Run, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() diff --git a/authorizer/task_test.go b/authorizer/task_test.go index a613e8524c6..c0b7721f092 100644 --- a/authorizer/task_test.go +++ b/authorizer/task_test.go @@ -2,6 +2,7 @@ package authorizer_test import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" "testing" "time" @@ -52,7 +53,7 @@ from(bucket:"holder") |> range(start:-5m) |> to(bucket:"holder", org:"thing")`, } } -func mockTaskService(orgID, taskID, runID influxdb.ID) influxdb.TaskService { +func mockTaskService(orgID, taskID, runID platform.ID) influxdb.TaskService { task := influxdb.Task{ ID: taskID, OrganizationID: orgID, @@ -79,7 +80,7 @@ from(bucket:"holder") |> range(start:-5m) |> to(bucket:"holder", org:"thing")`, } return &mock.TaskService{ - FindTaskByIDFn: func(context.Context, influxdb.ID) (*influxdb.Task, error) { + FindTaskByIDFn: func(context.Context, platform.ID) (*influxdb.Task, error) { return &task, nil }, FindTasksFn: func(context.Context, influxdb.TaskFilter) ([]*influxdb.Task, int, error) { @@ -89,10 +90,10 @@ from(bucket:"holder") |> range(start:-5m) |> to(bucket:"holder", org:"thing")`, taskCopy := task return &taskCopy, nil }, - UpdateTaskFn: func(context.Context, influxdb.ID, influxdb.TaskUpdate) (*influxdb.Task, error) { + UpdateTaskFn: func(context.Context, platform.ID, influxdb.TaskUpdate) (*influxdb.Task, error) { return &task, nil }, - DeleteTaskFn: func(context.Context, influxdb.ID) error { + DeleteTaskFn: func(context.Context, platform.ID) error { return nil }, FindLogsFn: func(context.Context, influxdb.LogFilter) ([]*influxdb.Log, int, error) { @@ -101,16 +102,16 @@ from(bucket:"holder") |> range(start:-5m) |> to(bucket:"holder", org:"thing")`, FindRunsFn: func(context.Context, influxdb.RunFilter) ([]*influxdb.Run, int, error) { return []*influxdb.Run{&run}, 1, nil }, - FindRunByIDFn: func(context.Context, influxdb.ID, influxdb.ID) (*influxdb.Run, error) { + FindRunByIDFn: func(context.Context, platform.ID, platform.ID) (*influxdb.Run, error) { return &run, nil }, - CancelRunFn: func(context.Context, influxdb.ID, influxdb.ID) error { + CancelRunFn: func(context.Context, platform.ID, platform.ID) error { return nil }, - RetryRunFn: func(context.Context, influxdb.ID, influxdb.ID) (*influxdb.Run, error) { + RetryRunFn: func(context.Context, platform.ID, platform.ID) (*influxdb.Run, error) { return &run, nil }, - ForceRunFn: func(context.Context, influxdb.ID, int64) (*influxdb.Run, error) { + ForceRunFn: func(context.Context, platform.ID, int64) (*influxdb.Run, error) { return &run, nil }, } @@ -118,8 +119,8 @@ from(bucket:"holder") |> range(start:-5m) |> to(bucket:"holder", org:"thing")`, func TestValidations(t *testing.T) { var ( - taskID = influxdb.ID(0x7456) - runID = influxdb.ID(0x402) + taskID = platform.ID(0x7456) + runID = platform.ID(0x402) otherOrg = &influxdb.Organization{Name: "other_org"} ) diff --git a/authorizer/telegraf.go b/authorizer/telegraf.go index 958692641b7..256eb7026b4 100644 --- a/authorizer/telegraf.go +++ b/authorizer/telegraf.go @@ -3,6 +3,8 @@ package authorizer import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -24,7 +26,7 @@ func NewTelegrafConfigService(s influxdb.TelegrafConfigStore, urm influxdb.UserR } // FindTelegrafConfigByID checks to see if the authorizer on context has read access to the id provided. -func (s *TelegrafConfigService) FindTelegrafConfigByID(ctx context.Context, id influxdb.ID) (*influxdb.TelegrafConfig, error) { +func (s *TelegrafConfigService) FindTelegrafConfigByID(ctx context.Context, id platform.ID) (*influxdb.TelegrafConfig, error) { tc, err := s.s.FindTelegrafConfigByID(ctx, id) if err != nil { return nil, err @@ -47,7 +49,7 @@ func (s *TelegrafConfigService) FindTelegrafConfigs(ctx context.Context, filter } // CreateTelegrafConfig checks to see if the authorizer on context has write access to the global telegraf config resource. -func (s *TelegrafConfigService) CreateTelegrafConfig(ctx context.Context, tc *influxdb.TelegrafConfig, userID influxdb.ID) error { +func (s *TelegrafConfigService) CreateTelegrafConfig(ctx context.Context, tc *influxdb.TelegrafConfig, userID platform.ID) error { if _, _, err := AuthorizeCreate(ctx, influxdb.TelegrafsResourceType, tc.OrgID); err != nil { return err } @@ -55,7 +57,7 @@ func (s *TelegrafConfigService) CreateTelegrafConfig(ctx context.Context, tc *in } // UpdateTelegrafConfig checks to see if the authorizer on context has write access to the telegraf config provided. -func (s *TelegrafConfigService) UpdateTelegrafConfig(ctx context.Context, id influxdb.ID, upd *influxdb.TelegrafConfig, userID influxdb.ID) (*influxdb.TelegrafConfig, error) { +func (s *TelegrafConfigService) UpdateTelegrafConfig(ctx context.Context, id platform.ID, upd *influxdb.TelegrafConfig, userID platform.ID) (*influxdb.TelegrafConfig, error) { tc, err := s.FindTelegrafConfigByID(ctx, id) if err != nil { return nil, err @@ -67,7 +69,7 @@ func (s *TelegrafConfigService) UpdateTelegrafConfig(ctx context.Context, id inf } // DeleteTelegrafConfig checks to see if the authorizer on context has write access to the telegraf config provided. -func (s *TelegrafConfigService) DeleteTelegrafConfig(ctx context.Context, id influxdb.ID) error { +func (s *TelegrafConfigService) DeleteTelegrafConfig(ctx context.Context, id platform.ID) error { tc, err := s.FindTelegrafConfigByID(ctx, id) if err != nil { return err diff --git a/authorizer/telegraf_test.go b/authorizer/telegraf_test.go index 64a00581fc8..26c0dbc69ba 100644 --- a/authorizer/telegraf_test.go +++ b/authorizer/telegraf_test.go @@ -3,6 +3,8 @@ package authorizer_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "sort" "testing" @@ -33,7 +35,7 @@ func TestTelegrafConfigStore_FindTelegrafConfigByID(t *testing.T) { } type args struct { permission influxdb.Permission - id influxdb.ID + id platform.ID } type wants struct { err error @@ -49,7 +51,7 @@ func TestTelegrafConfigStore_FindTelegrafConfigByID(t *testing.T) { name: "authorized to access id", fields: fields{ TelegrafConfigStore: &mock.TelegrafConfigStore{ - FindTelegrafConfigByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.TelegrafConfig, error) { + FindTelegrafConfigByIDF: func(ctx context.Context, id platform.ID) (*influxdb.TelegrafConfig, error) { return &influxdb.TelegrafConfig{ ID: id, OrgID: 10, @@ -75,7 +77,7 @@ func TestTelegrafConfigStore_FindTelegrafConfigByID(t *testing.T) { name: "unauthorized to access id", fields: fields{ TelegrafConfigStore: &mock.TelegrafConfigStore{ - FindTelegrafConfigByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.TelegrafConfig, error) { + FindTelegrafConfigByIDF: func(ctx context.Context, id platform.ID) (*influxdb.TelegrafConfig, error) { return &influxdb.TelegrafConfig{ ID: id, OrgID: 10, @@ -94,9 +96,9 @@ func TestTelegrafConfigStore_FindTelegrafConfigByID(t *testing.T) { id: 1, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/000000000000000a/telegrafs/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -248,7 +250,7 @@ func TestTelegrafConfigStore_UpdateTelegrafConfig(t *testing.T) { TelegrafConfigStore influxdb.TelegrafConfigStore } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -265,13 +267,13 @@ func TestTelegrafConfigStore_UpdateTelegrafConfig(t *testing.T) { name: "authorized to update telegraf", fields: fields{ TelegrafConfigStore: &mock.TelegrafConfigStore{ - FindTelegrafConfigByIDF: func(ctc context.Context, id influxdb.ID) (*influxdb.TelegrafConfig, error) { + FindTelegrafConfigByIDF: func(ctc context.Context, id platform.ID) (*influxdb.TelegrafConfig, error) { return &influxdb.TelegrafConfig{ ID: 1, OrgID: 10, }, nil }, - UpdateTelegrafConfigF: func(ctx context.Context, id influxdb.ID, upd *influxdb.TelegrafConfig, userID influxdb.ID) (*influxdb.TelegrafConfig, error) { + UpdateTelegrafConfigF: func(ctx context.Context, id platform.ID, upd *influxdb.TelegrafConfig, userID platform.ID) (*influxdb.TelegrafConfig, error) { return &influxdb.TelegrafConfig{ ID: 1, OrgID: 10, @@ -306,13 +308,13 @@ func TestTelegrafConfigStore_UpdateTelegrafConfig(t *testing.T) { name: "unauthorized to update telegraf", fields: fields{ TelegrafConfigStore: &mock.TelegrafConfigStore{ - FindTelegrafConfigByIDF: func(ctc context.Context, id influxdb.ID) (*influxdb.TelegrafConfig, error) { + FindTelegrafConfigByIDF: func(ctc context.Context, id platform.ID) (*influxdb.TelegrafConfig, error) { return &influxdb.TelegrafConfig{ ID: 1, OrgID: 10, }, nil }, - UpdateTelegrafConfigF: func(ctx context.Context, id influxdb.ID, upd *influxdb.TelegrafConfig, userID influxdb.ID) (*influxdb.TelegrafConfig, error) { + UpdateTelegrafConfigF: func(ctx context.Context, id platform.ID, upd *influxdb.TelegrafConfig, userID platform.ID) (*influxdb.TelegrafConfig, error) { return &influxdb.TelegrafConfig{ ID: 1, OrgID: 10, @@ -333,9 +335,9 @@ func TestTelegrafConfigStore_UpdateTelegrafConfig(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/telegrafs/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -348,7 +350,7 @@ func TestTelegrafConfigStore_UpdateTelegrafConfig(t *testing.T) { ctx := context.Background() ctx = influxdbcontext.SetAuthorizer(ctx, mock.NewMockAuthorizer(false, tt.args.permissions)) - _, err := s.UpdateTelegrafConfig(ctx, tt.args.id, &influxdb.TelegrafConfig{}, influxdb.ID(1)) + _, err := s.UpdateTelegrafConfig(ctx, tt.args.id, &influxdb.TelegrafConfig{}, platform.ID(1)) influxdbtesting.ErrorsEqual(t, err, tt.wants.err) }) } @@ -359,7 +361,7 @@ func TestTelegrafConfigStore_DeleteTelegrafConfig(t *testing.T) { TelegrafConfigStore influxdb.TelegrafConfigStore } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -376,13 +378,13 @@ func TestTelegrafConfigStore_DeleteTelegrafConfig(t *testing.T) { name: "authorized to delete telegraf", fields: fields{ TelegrafConfigStore: &mock.TelegrafConfigStore{ - FindTelegrafConfigByIDF: func(ctc context.Context, id influxdb.ID) (*influxdb.TelegrafConfig, error) { + FindTelegrafConfigByIDF: func(ctc context.Context, id platform.ID) (*influxdb.TelegrafConfig, error) { return &influxdb.TelegrafConfig{ ID: 1, OrgID: 10, }, nil }, - DeleteTelegrafConfigF: func(ctx context.Context, id influxdb.ID) error { + DeleteTelegrafConfigF: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -414,13 +416,13 @@ func TestTelegrafConfigStore_DeleteTelegrafConfig(t *testing.T) { name: "unauthorized to delete telegraf", fields: fields{ TelegrafConfigStore: &mock.TelegrafConfigStore{ - FindTelegrafConfigByIDF: func(ctc context.Context, id influxdb.ID) (*influxdb.TelegrafConfig, error) { + FindTelegrafConfigByIDF: func(ctc context.Context, id platform.ID) (*influxdb.TelegrafConfig, error) { return &influxdb.TelegrafConfig{ ID: 1, OrgID: 10, }, nil }, - DeleteTelegrafConfigF: func(ctx context.Context, id influxdb.ID) error { + DeleteTelegrafConfigF: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -438,9 +440,9 @@ func TestTelegrafConfigStore_DeleteTelegrafConfig(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/telegrafs/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -465,7 +467,7 @@ func TestTelegrafConfigStore_CreateTelegrafConfig(t *testing.T) { } type args struct { permission influxdb.Permission - orgID influxdb.ID + orgID platform.ID } type wants struct { err error @@ -481,7 +483,7 @@ func TestTelegrafConfigStore_CreateTelegrafConfig(t *testing.T) { name: "authorized to create telegraf", fields: fields{ TelegrafConfigStore: &mock.TelegrafConfigStore{ - CreateTelegrafConfigF: func(ctx context.Context, tc *influxdb.TelegrafConfig, userID influxdb.ID) error { + CreateTelegrafConfigF: func(ctx context.Context, tc *influxdb.TelegrafConfig, userID platform.ID) error { return nil }, }, @@ -504,7 +506,7 @@ func TestTelegrafConfigStore_CreateTelegrafConfig(t *testing.T) { name: "unauthorized to create telegraf", fields: fields{ TelegrafConfigStore: &mock.TelegrafConfigStore{ - CreateTelegrafConfigF: func(ctx context.Context, tc *influxdb.TelegrafConfig, userID influxdb.ID) error { + CreateTelegrafConfigF: func(ctx context.Context, tc *influxdb.TelegrafConfig, userID platform.ID) error { return nil }, }, @@ -520,9 +522,9 @@ func TestTelegrafConfigStore_CreateTelegrafConfig(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/telegrafs is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -535,7 +537,7 @@ func TestTelegrafConfigStore_CreateTelegrafConfig(t *testing.T) { ctx := context.Background() ctx = influxdbcontext.SetAuthorizer(ctx, mock.NewMockAuthorizer(false, []influxdb.Permission{tt.args.permission})) - err := s.CreateTelegrafConfig(ctx, &influxdb.TelegrafConfig{OrgID: tt.args.orgID}, influxdb.ID(1)) + err := s.CreateTelegrafConfig(ctx, &influxdb.TelegrafConfig{OrgID: tt.args.orgID}, platform.ID(1)) influxdbtesting.ErrorsEqual(t, err, tt.wants.err) }) } diff --git a/authorizer/urm.go b/authorizer/urm.go index b57097a3f9e..9bea567ec07 100644 --- a/authorizer/urm.go +++ b/authorizer/urm.go @@ -3,11 +3,13 @@ package authorizer import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) type OrgIDResolver interface { - FindResourceOrganizationID(ctx context.Context, rt influxdb.ResourceType, id influxdb.ID) (influxdb.ID, error) + FindResourceOrganizationID(ctx context.Context, rt influxdb.ResourceType, id platform.ID) (platform.ID, error) } type URMService struct { @@ -41,7 +43,7 @@ func (s *URMService) CreateUserResourceMapping(ctx context.Context, m *influxdb. return s.s.CreateUserResourceMapping(ctx, m) } -func (s *URMService) DeleteUserResourceMapping(ctx context.Context, resourceID influxdb.ID, userID influxdb.ID) error { +func (s *URMService) DeleteUserResourceMapping(ctx context.Context, resourceID platform.ID, userID platform.ID) error { f := influxdb.UserResourceMappingFilter{ResourceID: resourceID, UserID: userID} urms, _, err := s.s.FindUserResourceMappings(ctx, f) if err != nil { diff --git a/authorizer/urm_test.go b/authorizer/urm_test.go index e1dd7de79e6..d095fb2e1a7 100644 --- a/authorizer/urm_test.go +++ b/authorizer/urm_test.go @@ -2,6 +2,8 @@ package authorizer_test import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "testing" "github.com/google/go-cmp/cmp" @@ -13,10 +15,10 @@ import ( ) type OrgService struct { - OrgID influxdb.ID + OrgID platform.ID } -func (s *OrgService) FindResourceOrganizationID(ctx context.Context, rt influxdb.ResourceType, id influxdb.ID) (influxdb.ID, error) { +func (s *OrgService) FindResourceOrganizationID(ctx context.Context, rt influxdb.ResourceType, id platform.ID) (platform.ID, error) { return s.OrgID, nil } @@ -169,7 +171,7 @@ func TestURMService_WriteUserResourceMapping(t *testing.T) { CreateMappingFn: func(ctx context.Context, m *influxdb.UserResourceMapping) error { return nil }, - DeleteMappingFn: func(ctx context.Context, rid, uid influxdb.ID) error { + DeleteMappingFn: func(ctx context.Context, rid, uid platform.ID) error { return nil }, FindMappingsFn: func(ctx context.Context, filter influxdb.UserResourceMappingFilter) ([]*influxdb.UserResourceMapping, int, error) { @@ -204,7 +206,7 @@ func TestURMService_WriteUserResourceMapping(t *testing.T) { CreateMappingFn: func(ctx context.Context, m *influxdb.UserResourceMapping) error { return nil }, - DeleteMappingFn: func(ctx context.Context, rid, uid influxdb.ID) error { + DeleteMappingFn: func(ctx context.Context, rid, uid platform.ID) error { return nil }, FindMappingsFn: func(ctx context.Context, filter influxdb.UserResourceMappingFilter) ([]*influxdb.UserResourceMapping, int, error) { @@ -228,9 +230,9 @@ func TestURMService_WriteUserResourceMapping(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/buckets/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, diff --git a/authorizer/user.go b/authorizer/user.go index de3ba56cfe6..50a075548a6 100644 --- a/authorizer/user.go +++ b/authorizer/user.go @@ -3,6 +3,9 @@ package authorizer import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) @@ -22,7 +25,7 @@ func NewUserService(s influxdb.UserService) *UserService { } // FindUserByID checks to see if the authorizer on context has read access to the id provided. -func (s *UserService) FindUserByID(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { +func (s *UserService) FindUserByID(ctx context.Context, id platform.ID) (*influxdb.User, error) { if _, _, err := AuthorizeReadResource(ctx, influxdb.UsersResourceType, id); err != nil { return nil, err } @@ -61,7 +64,7 @@ func (s *UserService) CreateUser(ctx context.Context, o *influxdb.User) error { } // UpdateUser checks to see if the authorizer on context has write access to the user provided. -func (s *UserService) UpdateUser(ctx context.Context, id influxdb.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { +func (s *UserService) UpdateUser(ctx context.Context, id platform.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { if _, _, err := AuthorizeWriteResource(ctx, influxdb.UsersResourceType, id); err != nil { return nil, err } @@ -69,16 +72,16 @@ func (s *UserService) UpdateUser(ctx context.Context, id influxdb.ID, upd influx } // DeleteUser checks to see if the authorizer on context has write access to the user provided. -func (s *UserService) DeleteUser(ctx context.Context, id influxdb.ID) error { +func (s *UserService) DeleteUser(ctx context.Context, id platform.ID) error { if _, _, err := AuthorizeWriteResource(ctx, influxdb.UsersResourceType, id); err != nil { return err } return s.s.DeleteUser(ctx, id) } -func (s *UserService) FindPermissionForUser(ctx context.Context, uid influxdb.ID) (influxdb.PermissionSet, error) { - return nil, &influxdb.Error{ - Code: influxdb.EInternal, +func (s *UserService) FindPermissionForUser(ctx context.Context, uid platform.ID) (influxdb.PermissionSet, error) { + return nil, &errors.Error{ + Code: errors.EInternal, Msg: "not implemented", } } diff --git a/authorizer/user_test.go b/authorizer/user_test.go index 0f7e125816c..7438c2cf748 100644 --- a/authorizer/user_test.go +++ b/authorizer/user_test.go @@ -3,6 +3,8 @@ package authorizer_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "sort" "testing" @@ -33,7 +35,7 @@ func TestUserService_FindUserByID(t *testing.T) { } type args struct { permission influxdb.Permission - id influxdb.ID + id platform.ID } type wants struct { err error @@ -49,7 +51,7 @@ func TestUserService_FindUserByID(t *testing.T) { name: "authorized to access id", fields: fields{ UserService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ ID: id, }, nil @@ -74,7 +76,7 @@ func TestUserService_FindUserByID(t *testing.T) { name: "unauthorized to access id", fields: fields{ UserService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ ID: id, }, nil @@ -92,9 +94,9 @@ func TestUserService_FindUserByID(t *testing.T) { id: 1, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:users/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -175,9 +177,9 @@ func TestUserService_FindUser(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:users/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -315,7 +317,7 @@ func TestUserService_UpdateUser(t *testing.T) { UserService influxdb.UserService } type args struct { - id influxdb.ID + id platform.ID permission influxdb.Permission } type wants struct { @@ -332,7 +334,7 @@ func TestUserService_UpdateUser(t *testing.T) { name: "authorized to update user", fields: fields{ UserService: &mock.UserService{ - UpdateUserFn: func(ctx context.Context, id influxdb.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { + UpdateUserFn: func(ctx context.Context, id platform.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { return &influxdb.User{ ID: 1, }, nil @@ -357,7 +359,7 @@ func TestUserService_UpdateUser(t *testing.T) { name: "unauthorized to update user", fields: fields{ UserService: &mock.UserService{ - UpdateUserFn: func(ctx context.Context, id influxdb.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { + UpdateUserFn: func(ctx context.Context, id platform.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { return &influxdb.User{ ID: 1, }, nil @@ -375,9 +377,9 @@ func TestUserService_UpdateUser(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:users/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -401,7 +403,7 @@ func TestUserService_DeleteUser(t *testing.T) { UserService influxdb.UserService } type args struct { - id influxdb.ID + id platform.ID permission influxdb.Permission } type wants struct { @@ -418,7 +420,7 @@ func TestUserService_DeleteUser(t *testing.T) { name: "authorized to delete user", fields: fields{ UserService: &mock.UserService{ - DeleteUserFn: func(ctx context.Context, id influxdb.ID) error { + DeleteUserFn: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -441,7 +443,7 @@ func TestUserService_DeleteUser(t *testing.T) { name: "unauthorized to delete user", fields: fields{ UserService: &mock.UserService{ - DeleteUserFn: func(ctx context.Context, id influxdb.ID) error { + DeleteUserFn: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -457,9 +459,9 @@ func TestUserService_DeleteUser(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:users/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -535,9 +537,9 @@ func TestUserService_CreateUser(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:users is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, diff --git a/authorizer/variable.go b/authorizer/variable.go index 15b5cf37875..f5a61ffe468 100644 --- a/authorizer/variable.go +++ b/authorizer/variable.go @@ -3,6 +3,8 @@ package authorizer import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -22,7 +24,7 @@ func NewVariableService(s influxdb.VariableService) *VariableService { } // FindVariableByID checks to see if the authorizer on context has read access to the id provided. -func (s *VariableService) FindVariableByID(ctx context.Context, id influxdb.ID) (*influxdb.Variable, error) { +func (s *VariableService) FindVariableByID(ctx context.Context, id platform.ID) (*influxdb.Variable, error) { v, err := s.s.FindVariableByID(ctx, id) if err != nil { return nil, err @@ -53,7 +55,7 @@ func (s *VariableService) CreateVariable(ctx context.Context, v *influxdb.Variab } // UpdateVariable checks to see if the authorizer on context has write access to the variable provided. -func (s *VariableService) UpdateVariable(ctx context.Context, id influxdb.ID, upd *influxdb.VariableUpdate) (*influxdb.Variable, error) { +func (s *VariableService) UpdateVariable(ctx context.Context, id platform.ID, upd *influxdb.VariableUpdate) (*influxdb.Variable, error) { v, err := s.FindVariableByID(ctx, id) if err != nil { return nil, err @@ -77,7 +79,7 @@ func (s *VariableService) ReplaceVariable(ctx context.Context, m *influxdb.Varia } // DeleteVariable checks to see if the authorizer on context has write access to the variable provided. -func (s *VariableService) DeleteVariable(ctx context.Context, id influxdb.ID) error { +func (s *VariableService) DeleteVariable(ctx context.Context, id platform.ID) error { v, err := s.FindVariableByID(ctx, id) if err != nil { return err diff --git a/authorizer/variable_test.go b/authorizer/variable_test.go index c5cf261f019..a846f3fd6d4 100644 --- a/authorizer/variable_test.go +++ b/authorizer/variable_test.go @@ -3,6 +3,8 @@ package authorizer_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "sort" "testing" @@ -33,7 +35,7 @@ func TestVariableService_FindVariableByID(t *testing.T) { } type args struct { permission influxdb.Permission - id influxdb.ID + id platform.ID } type wants struct { err error @@ -49,7 +51,7 @@ func TestVariableService_FindVariableByID(t *testing.T) { name: "authorized to access id", fields: fields{ VariableService: &mock.VariableService{ - FindVariableByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Variable, error) { + FindVariableByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Variable, error) { return &influxdb.Variable{ ID: id, OrganizationID: 10, @@ -75,7 +77,7 @@ func TestVariableService_FindVariableByID(t *testing.T) { name: "unauthorized to access id", fields: fields{ VariableService: &mock.VariableService{ - FindVariableByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Variable, error) { + FindVariableByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Variable, error) { return &influxdb.Variable{ ID: id, OrganizationID: 10, @@ -94,9 +96,9 @@ func TestVariableService_FindVariableByID(t *testing.T) { id: 1, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/000000000000000a/variables/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -248,7 +250,7 @@ func TestVariableService_UpdateVariable(t *testing.T) { VariableService influxdb.VariableService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -265,13 +267,13 @@ func TestVariableService_UpdateVariable(t *testing.T) { name: "authorized to update variable", fields: fields{ VariableService: &mock.VariableService{ - FindVariableByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Variable, error) { + FindVariableByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Variable, error) { return &influxdb.Variable{ ID: 1, OrganizationID: 10, }, nil }, - UpdateVariableF: func(ctx context.Context, id influxdb.ID, upd *influxdb.VariableUpdate) (*influxdb.Variable, error) { + UpdateVariableF: func(ctx context.Context, id platform.ID, upd *influxdb.VariableUpdate) (*influxdb.Variable, error) { return &influxdb.Variable{ ID: 1, OrganizationID: 10, @@ -306,13 +308,13 @@ func TestVariableService_UpdateVariable(t *testing.T) { name: "unauthorized to update variable", fields: fields{ VariableService: &mock.VariableService{ - FindVariableByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Variable, error) { + FindVariableByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Variable, error) { return &influxdb.Variable{ ID: 1, OrganizationID: 10, }, nil }, - UpdateVariableF: func(ctx context.Context, id influxdb.ID, upd *influxdb.VariableUpdate) (*influxdb.Variable, error) { + UpdateVariableF: func(ctx context.Context, id platform.ID, upd *influxdb.VariableUpdate) (*influxdb.Variable, error) { return &influxdb.Variable{ ID: 1, OrganizationID: 10, @@ -333,9 +335,9 @@ func TestVariableService_UpdateVariable(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/variables/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -376,7 +378,7 @@ func TestVariableService_ReplaceVariable(t *testing.T) { name: "authorized to replace variable", fields: fields{ VariableService: &mock.VariableService{ - FindVariableByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Variable, error) { + FindVariableByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Variable, error) { return &influxdb.Variable{ ID: 1, OrganizationID: 10, @@ -418,7 +420,7 @@ func TestVariableService_ReplaceVariable(t *testing.T) { name: "unauthorized to replace variable", fields: fields{ VariableService: &mock.VariableService{ - FindVariableByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Variable, error) { + FindVariableByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Variable, error) { return &influxdb.Variable{ ID: 1, OrganizationID: 10, @@ -445,9 +447,9 @@ func TestVariableService_ReplaceVariable(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/variables/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -471,7 +473,7 @@ func TestVariableService_DeleteVariable(t *testing.T) { VariableService influxdb.VariableService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -488,13 +490,13 @@ func TestVariableService_DeleteVariable(t *testing.T) { name: "authorized to delete variable", fields: fields{ VariableService: &mock.VariableService{ - FindVariableByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Variable, error) { + FindVariableByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Variable, error) { return &influxdb.Variable{ ID: 1, OrganizationID: 10, }, nil }, - DeleteVariableF: func(ctx context.Context, id influxdb.ID) error { + DeleteVariableF: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -526,13 +528,13 @@ func TestVariableService_DeleteVariable(t *testing.T) { name: "unauthorized to delete variable", fields: fields{ VariableService: &mock.VariableService{ - FindVariableByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Variable, error) { + FindVariableByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Variable, error) { return &influxdb.Variable{ ID: 1, OrganizationID: 10, }, nil }, - DeleteVariableF: func(ctx context.Context, id influxdb.ID) error { + DeleteVariableF: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -550,9 +552,9 @@ func TestVariableService_DeleteVariable(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/variables/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -577,7 +579,7 @@ func TestVariableService_CreateVariable(t *testing.T) { } type args struct { permission influxdb.Permission - orgID influxdb.ID + orgID platform.ID } type wants struct { err error @@ -632,9 +634,9 @@ func TestVariableService_CreateVariable(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/variables is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, diff --git a/authz.go b/authz.go index c70cb200f13..4489e0c910c 100644 --- a/authz.go +++ b/authz.go @@ -5,6 +5,9 @@ import ( "fmt" "os" "path/filepath" + + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" ) var ( @@ -22,10 +25,10 @@ type Authorizer interface { PermissionSet() (PermissionSet, error) // ID returns an identifier used for auditing. - Identifier() ID + Identifier() platform.ID // GetUserID returns the user id. - GetUserID() ID + GetUserID() platform.ID // Kind metadata for auditing. Kind() string @@ -74,8 +77,8 @@ type ResourceType string // Resource is an authorizable resource. type Resource struct { Type ResourceType `json:"type"` - ID *ID `json:"id,omitempty"` - OrgID *ID `json:"orgID,omitempty"` + ID *platform.ID `json:"id,omitempty"` + OrgID *platform.ID `json:"orgID,omitempty"` } // String stringifies a resource @@ -330,33 +333,33 @@ func (p Permission) String() string { // Valid checks if there the resource and action provided is known. func (p *Permission) Valid() error { if err := p.Resource.Valid(); err != nil { - return &Error{ - Code: EInvalid, + return &errors2.Error{ + Code: errors2.EInvalid, Err: err, Msg: "invalid resource type for permission", } } if err := p.Action.Valid(); err != nil { - return &Error{ - Code: EInvalid, + return &errors2.Error{ + Code: errors2.EInvalid, Err: err, Msg: "invalid action type for permission", } } if p.Resource.OrgID != nil && !p.Resource.OrgID.Valid() { - return &Error{ - Code: EInvalid, - Err: ErrInvalidID, + return &errors2.Error{ + Code: errors2.EInvalid, + Err: platform.ErrInvalidID, Msg: "invalid org id for permission", } } if p.Resource.ID != nil && !p.Resource.ID.Valid() { - return &Error{ - Code: EInvalid, - Err: ErrInvalidID, + return &errors2.Error{ + Code: errors2.EInvalid, + Err: platform.ErrInvalidID, Msg: "invalid id for permission", } } @@ -365,7 +368,7 @@ func (p *Permission) Valid() error { } // NewPermission returns a permission with provided arguments. -func NewPermission(a Action, rt ResourceType, orgID ID) (*Permission, error) { +func NewPermission(a Action, rt ResourceType, orgID platform.ID) (*Permission, error) { p := &Permission{ Action: a, Resource: Resource{ @@ -378,7 +381,7 @@ func NewPermission(a Action, rt ResourceType, orgID ID) (*Permission, error) { } // NewResourcePermission returns a permission with provided arguments. -func NewResourcePermission(a Action, rt ResourceType, rid ID) (*Permission, error) { +func NewResourcePermission(a Action, rt ResourceType, rid platform.ID) (*Permission, error) { p := &Permission{ Action: a, Resource: Resource{ @@ -402,7 +405,7 @@ func NewGlobalPermission(a Action, rt ResourceType) (*Permission, error) { } // NewPermissionAtID creates a permission with the provided arguments. -func NewPermissionAtID(id ID, a Action, rt ResourceType, orgID ID) (*Permission, error) { +func NewPermissionAtID(id platform.ID, a Action, rt ResourceType, orgID platform.ID) (*Permission, error) { p := &Permission{ Action: a, Resource: Resource{ @@ -438,7 +441,7 @@ func ReadAllPermissions() []Permission { } // OwnerPermissions are the default permissions for those who own a resource. -func OwnerPermissions(orgID ID) []Permission { +func OwnerPermissions(orgID platform.ID) []Permission { ps := []Permission{} for _, r := range AllResourceTypes { for _, a := range actions { @@ -453,7 +456,7 @@ func OwnerPermissions(orgID ID) []Permission { } // MePermissions is the permission to read/write myself. -func MePermissions(userID ID) []Permission { +func MePermissions(userID platform.ID) []Permission { ps := []Permission{} for _, a := range actions { ps = append(ps, Permission{Action: a, Resource: Resource{Type: UsersResourceType, ID: &userID}}) @@ -463,7 +466,7 @@ func MePermissions(userID ID) []Permission { } // MemberPermissions are the default permissions for those who can see a resource. -func MemberPermissions(orgID ID) []Permission { +func MemberPermissions(orgID platform.ID) []Permission { ps := []Permission{} for _, r := range AllResourceTypes { if r == OrgsResourceType { @@ -477,6 +480,6 @@ func MemberPermissions(orgID ID) []Permission { } // MemberPermissions are the default permissions for those who can see a resource. -func MemberBucketPermission(bucketID ID) Permission { +func MemberBucketPermission(bucketID platform.ID) Permission { return Permission{Action: ReadAction, Resource: Resource{Type: BucketsResourceType, ID: &bucketID}} } diff --git a/authz_test.go b/authz_test.go index 93c1327c3bb..426e3cef7ab 100644 --- a/authz_test.go +++ b/authz_test.go @@ -1,6 +1,7 @@ package influxdb_test import ( + platform2 "github.com/influxdata/influxdb/v2/kit/platform" "testing" platform "github.com/influxdata/influxdb/v2" @@ -279,7 +280,7 @@ func TestPermission_Valid(t *testing.T) { Action: platform.WriteAction, Resource: platform.Resource{ Type: platform.BucketsResourceType, - ID: func() *platform.ID { id := platform.InvalidID(); return &id }(), + ID: func() *platform2.ID { id := platform2.InvalidID(); return &id }(), OrgID: influxdbtesting.IDPtr(1), }, }, @@ -431,7 +432,7 @@ func TestPermission_String(t *testing.T) { } } -func validID() *platform.ID { - id := platform.ID(100) +func validID() *platform2.ID { + id := platform2.ID(100) return &id } diff --git a/backup.go b/backup.go index 741fc441034..d22a67f8e3e 100644 --- a/backup.go +++ b/backup.go @@ -4,6 +4,8 @@ import ( "context" "io" "time" + + "github.com/influxdata/influxdb/v2/kit/platform" ) const ( @@ -25,7 +27,7 @@ type RestoreService interface { RestoreKVStore(ctx context.Context, r io.Reader) error // RestoreKVStore restores the metadata database. - RestoreBucket(ctx context.Context, id ID, rpiData []byte) (shardIDMap map[uint64]uint64, err error) + RestoreBucket(ctx context.Context, id platform.ID, rpiData []byte) (shardIDMap map[uint64]uint64, err error) // RestoreShard uploads a backup file for a single shard. RestoreShard(ctx context.Context, shardID uint64, r io.Reader) error diff --git a/backup/backup.go b/backup/backup.go index 1d52f71ef74..0e25a4d4b9c 100644 --- a/backup/backup.go +++ b/backup/backup.go @@ -10,6 +10,9 @@ import ( "path/filepath" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/bolt" "github.com/influxdata/influxdb/v2/tenant" @@ -20,12 +23,12 @@ import ( type Request struct { // Organization to backup. // If not set, all orgs will be included. - OrgID influxdb.ID + OrgID platform.ID Org string // Bucket to backup. // If not set, all buckets within the org filter will be included. - BucketID influxdb.ID + BucketID platform.ID Bucket string // Path to the directory where backup files should be written. @@ -210,7 +213,7 @@ func (r *backupRunner) backupShard(ctx context.Context, shardInfo *influxdb.Mani _ = gw.Close() _ = f.Close() - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors.ErrorCode(err) == errors.ENotFound { r.log.Warn("Shard removed during backup", zap.Uint64("id", shardInfo.ShardID)) return nil } diff --git a/bolt/bbolt.go b/bolt/bbolt.go index d1ab6863e00..7da4039d68c 100644 --- a/bolt/bbolt.go +++ b/bolt/bbolt.go @@ -7,6 +7,8 @@ import ( "path/filepath" "time" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/rand" "github.com/influxdata/influxdb/v2/snowflake" @@ -22,7 +24,7 @@ type Client struct { db *bolt.DB log *zap.Logger - IDGenerator platform.IDGenerator + IDGenerator platform2.IDGenerator TokenGenerator platform.TokenGenerator platform.TimeGenerator diff --git a/bolt/id.go b/bolt/id.go index 23d8aabbaaf..a7bf8f2dd0a 100644 --- a/bolt/id.go +++ b/bolt/id.go @@ -5,7 +5,8 @@ import ( "fmt" "math/rand" - platform "github.com/influxdata/influxdb/v2" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + bolt "go.etcd.io/bbolt" "go.uber.org/zap" ) @@ -16,7 +17,7 @@ var ( errIDNotFound = errors.New("source not found") ) -var _ platform.IDGenerator = (*Client)(nil) +var _ platform2.IDGenerator = (*Client)(nil) func (c *Client) initializeID(tx *bolt.Tx) error { if _, err := tx.CreateBucketIfNotExists(idsBucket); err != nil { @@ -38,9 +39,9 @@ func (c *Client) initializeID(tx *bolt.Tx) error { } // ID retrieves the unique ID for this influx instance. -func (c *Client) ID() platform.ID { +func (c *Client) ID() platform2.ID { // if any error occurs return a random number - id := platform.ID(rand.Int63()) + id := platform2.ID(rand.Int63()) err := c.db.View(func(tx *bolt.Tx) error { val, err := c.getID(tx) if err != nil { @@ -58,23 +59,23 @@ func (c *Client) ID() platform.ID { return id } -func (c *Client) getID(tx *bolt.Tx) (platform.ID, error) { +func (c *Client) getID(tx *bolt.Tx) (platform2.ID, error) { v := tx.Bucket(idsBucket).Get(idKey) if len(v) == 0 { - return platform.InvalidID(), errIDNotFound + return platform2.InvalidID(), errIDNotFound } return decodeID(v) } -func decodeID(val []byte) (platform.ID, error) { - if len(val) < platform.IDLength { +func decodeID(val []byte) (platform2.ID, error) { + if len(val) < platform2.IDLength { // This should not happen. - return platform.InvalidID(), fmt.Errorf("provided value is too short to contain an ID. Please report this error") + return platform2.InvalidID(), fmt.Errorf("provided value is too short to contain an ID. Please report this error") } - var id platform.ID - if err := id.Decode(val[:platform.IDLength]); err != nil { - return platform.InvalidID(), err + var id platform2.ID + if err := id.Decode(val[:platform2.IDLength]); err != nil { + return platform2.InvalidID(), err } return id, nil } diff --git a/bolt/id_test.go b/bolt/id_test.go index daf98993223..44c5a801c09 100644 --- a/bolt/id_test.go +++ b/bolt/id_test.go @@ -2,9 +2,9 @@ package bolt_test import ( "context" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" "testing" - platform "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" ) @@ -15,7 +15,7 @@ func TestID(t *testing.T) { } defer closeFn() - testID := platform.ID(70000) + testID := platform2.ID(70000) c.IDGenerator = mock.NewIDGenerator(testID.String(), t) if err := c.Open(context.Background()); err != nil { diff --git a/bucket.go b/bucket.go index 097a6415b89..095a9034f8e 100644 --- a/bucket.go +++ b/bucket.go @@ -5,6 +5,9 @@ import ( "fmt" "strings" "time" + + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) const ( @@ -29,8 +32,8 @@ const InfiniteRetention = 0 // Bucket is a bucket. 🎉 type Bucket struct { - ID ID `json:"id,omitempty"` - OrgID ID `json:"orgID,omitempty"` + ID platform.ID `json:"id,omitempty"` + OrgID platform.ID `json:"orgID,omitempty"` Type BucketType `json:"type"` Name string `json:"name"` Description string `json:"description"` @@ -79,7 +82,7 @@ var ( // BucketService represents a service for managing bucket data. type BucketService interface { // FindBucketByID returns a single bucket by ID. - FindBucketByID(ctx context.Context, id ID) (*Bucket, error) + FindBucketByID(ctx context.Context, id platform.ID) (*Bucket, error) // FindBucket returns the first bucket that matches filter. FindBucket(ctx context.Context, filter BucketFilter) (*Bucket, error) @@ -93,11 +96,11 @@ type BucketService interface { // UpdateBucket updates a single bucket with changeset. // Returns the new bucket state after update. - UpdateBucket(ctx context.Context, id ID, upd BucketUpdate) (*Bucket, error) + UpdateBucket(ctx context.Context, id platform.ID, upd BucketUpdate) (*Bucket, error) // DeleteBucket removes a bucket by ID. - DeleteBucket(ctx context.Context, id ID) error - FindBucketByName(ctx context.Context, orgID ID, name string) (*Bucket, error) + DeleteBucket(ctx context.Context, id platform.ID) error + FindBucketByName(ctx context.Context, orgID platform.ID, name string) (*Bucket, error) } // BucketUpdate represents updates to a bucket. @@ -111,9 +114,9 @@ type BucketUpdate struct { // BucketFilter represents a set of filter that restrict the returned results. type BucketFilter struct { - ID *ID + ID *platform.ID Name *string - OrganizationID *ID + OrganizationID *platform.ID Org *string } @@ -159,9 +162,9 @@ func (f BucketFilter) String() string { return "[" + strings.Join(parts, ", ") + "]" } -func ErrInternalBucketServiceError(op string, err error) *Error { - return &Error{ - Code: EInternal, +func ErrInternalBucketServiceError(op string, err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("unexpected error in buckets; Err: %v", err), Op: op, Err: err, diff --git a/check.go b/check.go index 24fcd95ec99..134e28e0077 100644 --- a/check.go +++ b/check.go @@ -3,6 +3,9 @@ package influxdb import ( "context" "encoding/json" + + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) // consts for checks config. @@ -16,22 +19,22 @@ type Check interface { Valid(lang FluxLanguageService) error Type() string ClearPrivateData() - SetTaskID(ID) - GetTaskID() ID - GetOwnerID() ID - SetOwnerID(ID) + SetTaskID(platform.ID) + GetTaskID() platform.ID + GetOwnerID() platform.ID + SetOwnerID(platform.ID) GenerateFlux(lang FluxLanguageService) (string, error) json.Marshaler CRUDLogSetter - SetID(id ID) - SetOrgID(id ID) + SetID(id platform.ID) + SetOrgID(id platform.ID) SetName(name string) SetDescription(description string) - GetID() ID + GetID() platform.ID GetCRUDLog() CRUDLog - GetOrgID() ID + GetOrgID() platform.ID GetName() string GetDescription() string } @@ -49,7 +52,7 @@ var ( // CheckService represents a service for managing checks. type CheckService interface { // FindCheckByID returns a single check by ID. - FindCheckByID(ctx context.Context, id ID) (Check, error) + FindCheckByID(ctx context.Context, id platform.ID) (Check, error) // FindCheck returns the first check that matches filter. FindCheck(ctx context.Context, filter CheckFilter) (Check, error) @@ -59,18 +62,18 @@ type CheckService interface { FindChecks(ctx context.Context, filter CheckFilter, opt ...FindOptions) ([]Check, int, error) // CreateCheck creates a new check and sets b.ID with the new identifier. - CreateCheck(ctx context.Context, c CheckCreate, userID ID) error + CreateCheck(ctx context.Context, c CheckCreate, userID platform.ID) error // UpdateCheck updates the whole check. // Returns the new check state after update. - UpdateCheck(ctx context.Context, id ID, c CheckCreate) (Check, error) + UpdateCheck(ctx context.Context, id platform.ID, c CheckCreate) (Check, error) // PatchCheck updates a single bucket with changeset. // Returns the new check state after update. - PatchCheck(ctx context.Context, id ID, upd CheckUpdate) (Check, error) + PatchCheck(ctx context.Context, id platform.ID, upd CheckUpdate) (Check, error) // DeleteCheck will delete the check by id. - DeleteCheck(ctx context.Context, id ID) error + DeleteCheck(ctx context.Context, id platform.ID) error } // CheckUpdate are properties than can be updated on a check @@ -89,15 +92,15 @@ type CheckCreate struct { // Valid returns err is the update is invalid. func (n *CheckUpdate) Valid() error { if n.Name != nil && *n.Name == "" { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Check Name can't be empty", } } if n.Description != nil && *n.Description == "" { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Check Description can't be empty", } } @@ -113,9 +116,9 @@ func (n *CheckUpdate) Valid() error { // CheckFilter represents a set of filters that restrict the returned results. type CheckFilter struct { - ID *ID + ID *platform.ID Name *string - OrgID *ID + OrgID *platform.ID Org *string UserResourceMappingFilter } diff --git a/checks/service.go b/checks/service.go index 98ad8964594..02e658057ee 100644 --- a/checks/service.go +++ b/checks/service.go @@ -4,6 +4,9 @@ import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/tracing" "github.com/influxdata/influxdb/v2/kv" @@ -26,7 +29,7 @@ type Service struct { tasks influxdb.TaskService timeGenerator influxdb.TimeGenerator - idGenerator influxdb.IDGenerator + idGenerator platform.IDGenerator checkStore *kv.IndexStore } @@ -83,7 +86,7 @@ func newCheckStore() *kv.IndexStore { } // FindCheckByID retrieves a check by id. -func (s *Service) FindCheckByID(ctx context.Context, id influxdb.ID) (influxdb.Check, error) { +func (s *Service) FindCheckByID(ctx context.Context, id platform.ID) (influxdb.Check, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -103,7 +106,7 @@ func (s *Service) FindCheckByID(ctx context.Context, id influxdb.ID) (influxdb.C return c, nil } -func (s *Service) findCheckByID(ctx context.Context, tx kv.Tx, id influxdb.ID) (influxdb.Check, error) { +func (s *Service) findCheckByID(ctx context.Context, tx kv.Tx, id platform.ID) (influxdb.Check, error) { chkVal, err := s.checkStore.FindEnt(ctx, tx, kv.Entity{PK: kv.EncID(id)}) if err != nil { return nil, err @@ -111,7 +114,7 @@ func (s *Service) findCheckByID(ctx context.Context, tx kv.Tx, id influxdb.ID) ( return chkVal.(influxdb.Check), nil } -func (s *Service) findCheckByName(ctx context.Context, tx kv.Tx, orgID influxdb.ID, name string) (influxdb.Check, error) { +func (s *Service) findCheckByName(ctx context.Context, tx kv.Tx, orgID platform.ID, name string) (influxdb.Check, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -119,8 +122,8 @@ func (s *Service) findCheckByName(ctx context.Context, tx kv.Tx, orgID influxdb. UniqueKey: kv.Encode(kv.EncID(orgID), kv.EncString(name)), }) if kv.IsNotFound(err) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Err: err, } } @@ -186,8 +189,8 @@ func (s *Service) FindCheck(ctx context.Context, filter influxdb.CheckFilter) (i } if c == nil { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: "check not found", } } @@ -227,7 +230,7 @@ func (s *Service) FindChecks(ctx context.Context, filter influxdb.CheckFilter, o if filter.Org != nil { o, err := s.orgs.FindOrganization(ctx, influxdb.OrganizationFilter{Name: filter.Org}) if err != nil { - return nil, 0, &influxdb.Error{Err: err} + return nil, 0, &errors.Error{Err: err} } filter.OrgID = &o.ID @@ -270,7 +273,7 @@ func (s *Service) FindChecks(ctx context.Context, filter influxdb.CheckFilter, o } // CreateCheck creates a influxdb check and sets ID. -func (s *Service) CreateCheck(ctx context.Context, c influxdb.CheckCreate, userID influxdb.ID) (err error) { +func (s *Service) CreateCheck(ctx context.Context, c influxdb.CheckCreate, userID platform.ID) (err error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -280,8 +283,8 @@ func (s *Service) CreateCheck(ctx context.Context, c influxdb.CheckCreate, userI if c.GetOrgID().Valid() { if _, err := s.orgs.FindOrganizationByID(ctx, c.GetOrgID()); err != nil { - return &influxdb.Error{ - Code: influxdb.ENotFound, + return &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpCreateCheck, Err: err, } @@ -301,8 +304,8 @@ func (s *Service) CreateCheck(ctx context.Context, c influxdb.CheckCreate, userI // create task initially in inactive state t, err := s.createCheckTask(ctx, c) if err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Could not create task from check", Err: err, } @@ -378,7 +381,7 @@ func (s *Service) putCheck(ctx context.Context, tx kv.Tx, c influxdb.Check, opts } // PatchCheck updates a check according the parameters set on upd. -func (s *Service) PatchCheck(ctx context.Context, id influxdb.ID, upd influxdb.CheckUpdate) (influxdb.Check, error) { +func (s *Service) PatchCheck(ctx context.Context, id platform.ID, upd influxdb.CheckUpdate) (influxdb.Check, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -408,7 +411,7 @@ func (s *Service) PatchCheck(ctx context.Context, id influxdb.ID, upd influxdb.C } // UpdateCheck updates the check. -func (s *Service) UpdateCheck(ctx context.Context, id influxdb.ID, chk influxdb.CheckCreate) (influxdb.Check, error) { +func (s *Service) UpdateCheck(ctx context.Context, id platform.ID, chk influxdb.CheckCreate) (influxdb.Check, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -453,7 +456,7 @@ func (s *Service) updateCheckTask(ctx context.Context, chk influxdb.CheckCreate) return err } -func (s *Service) patchCheckTask(ctx context.Context, taskID influxdb.ID, upd influxdb.CheckUpdate) error { +func (s *Service) patchCheckTask(ctx context.Context, taskID platform.ID, upd influxdb.CheckUpdate) error { tu := influxdb.TaskUpdate{ Description: upd.Description, } @@ -469,7 +472,7 @@ func (s *Service) patchCheckTask(ctx context.Context, taskID influxdb.ID, upd in return nil } -func (s *Service) updateCheck(ctx context.Context, tx kv.Tx, id influxdb.ID, chk influxdb.CheckCreate) (influxdb.Check, error) { +func (s *Service) updateCheck(ctx context.Context, tx kv.Tx, id platform.ID, chk influxdb.CheckCreate) (influxdb.Check, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -483,8 +486,8 @@ func (s *Service) updateCheck(ctx context.Context, tx kv.Tx, id influxdb.ID, chk if chk.GetName() != current.GetName() { c0, err := s.findCheckByName(ctx, tx, current.GetOrgID(), chk.GetName()) if err == nil && c0.GetID() != id { - return nil, &influxdb.Error{ - Code: influxdb.EConflict, + return nil, &errors.Error{ + Code: errors.EConflict, Msg: "check name is not unique", } } @@ -542,7 +545,7 @@ func (s *Service) patchCheck(ctx context.Context, tx kv.Tx, check influxdb.Check } // DeleteCheck deletes a check and prunes it from the index. -func (s *Service) DeleteCheck(ctx context.Context, id influxdb.ID) error { +func (s *Service) DeleteCheck(ctx context.Context, id platform.ID) error { ch, err := s.FindCheckByID(ctx, id) if err != nil { return err diff --git a/checks/service_external_test.go b/checks/service_external_test.go index e7c82c3bb9c..b361ef47292 100644 --- a/checks/service_external_test.go +++ b/checks/service_external_test.go @@ -8,6 +8,9 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/influxdata/flux/ast" @@ -174,7 +177,7 @@ var taskCmpOptions = cmp.Options{ // CheckFields will include the IDGenerator, and checks type CheckFields struct { - IDGenerator influxdb.IDGenerator + IDGenerator platform.IDGenerator TimeGenerator influxdb.TimeGenerator TaskService influxdb.TaskService Checks []influxdb.Check @@ -240,11 +243,11 @@ func CreateCheck( t *testing.T, ) { type args struct { - userID influxdb.ID + userID platform.ID check influxdb.Check } type wants struct { - err *influxdb.Error + err *errors.Error checks []influxdb.Check tasks []*influxdb.Task } @@ -369,7 +372,7 @@ func CreateCheck( name: "basic create check", fields: CheckFields{ IDGenerator: &mock.IDGenerator{ - IDFn: func() influxdb.ID { + IDFn: func() platform.ID { return MustIDBase16(checkTwoID) }, }, @@ -453,7 +456,7 @@ func CreateCheck( name: "names should be unique within an organization", fields: CheckFields{ IDGenerator: &mock.IDGenerator{ - IDFn: func() influxdb.ID { + IDFn: func() platform.ID { return MustIDBase16(checkTwoID) }, }, @@ -508,8 +511,8 @@ func CreateCheck( checks: []influxdb.Check{ deadman1, }, - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Op: influxdb.OpCreateCheck, Msg: "check is not unique", }, @@ -519,7 +522,7 @@ func CreateCheck( name: "names should not be unique across organizations", fields: CheckFields{ IDGenerator: &mock.IDGenerator{ - IDFn: func() influxdb.ID { + IDFn: func() platform.ID { return MustIDBase16(checkTwoID) }, }, @@ -670,8 +673,8 @@ func CreateCheck( }, wants: wants{ checks: []influxdb.Check{}, - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "organization not found", Op: influxdb.OpCreateCheck, }, @@ -716,10 +719,10 @@ func FindCheckByID( t *testing.T, ) { type args struct { - id influxdb.ID + id platform.ID } type wants struct { - err *influxdb.Error + err *errors.Error check influxdb.Check } @@ -768,8 +771,8 @@ func FindCheckByID( id: MustIDBase16(threeID), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindCheckByID, Msg: "check not found", }, @@ -799,11 +802,11 @@ func FindChecks( t *testing.T, ) { type args struct { - ID influxdb.ID + ID platform.ID name string organization string - OrgID influxdb.ID - userID influxdb.ID + OrgID platform.ID + userID platform.ID findOptions influxdb.FindOptions } @@ -1034,10 +1037,10 @@ func DeleteCheck( ) { type args struct { ID string - userID influxdb.ID + userID platform.ID } type wants struct { - err *influxdb.Error + err *errors.Error checks []influxdb.Check } @@ -1108,10 +1111,10 @@ data = from(bucket: "telegraf") |> range(start: -1m)`, userID: MustIDBase16(sixID), }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Op: influxdb.OpDeleteCheck, Msg: "check not found", - Code: influxdb.ENotFound, + Code: errors.ENotFound, }, checks: []influxdb.Check{ deadman1, @@ -1148,12 +1151,12 @@ func FindCheck( ) { type args struct { name string - OrgID influxdb.ID + OrgID platform.ID } type wants struct { check influxdb.Check - err *influxdb.Error + err *errors.Error } tests := []struct { @@ -1204,8 +1207,8 @@ func FindCheck( OrgID: MustIDBase16(orgOneID), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindCheck, Msg: "check not found", }, @@ -1227,8 +1230,8 @@ func FindCheck( OrgID: MustIDBase16(orgOneID), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindCheck, Msg: "check not found", }, @@ -1265,7 +1268,7 @@ func UpdateCheck( t *testing.T, ) { type args struct { - id influxdb.ID + id platform.ID check influxdb.Check } type wants struct { @@ -1495,8 +1498,8 @@ data = from(bucket: "telegraf") |> range(start: -1m)`, }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Msg: "check name is not unique", }, }, @@ -1527,11 +1530,11 @@ func PatchCheck( t *testing.T, ) { type args struct { - id influxdb.ID + id platform.ID upd influxdb.CheckUpdate } type wants struct { - err *influxdb.Error + err *errors.Error check influxdb.Check } @@ -1667,8 +1670,8 @@ data = from(bucket: "telegraf") |> range(start: -1m)`, }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Msg: "check entity update conflicts with an existing entity", }, }, @@ -1692,8 +1695,8 @@ data = from(bucket: "telegraf") |> range(start: -1m)`, } // MustIDBase16 is an helper to ensure a correct ID is built during testing. -func MustIDBase16(s string) influxdb.ID { - id, err := influxdb.IDFromString(s) +func MustIDBase16(s string) platform.ID { + id, err := platform.IDFromString(s) if err != nil { panic(err) } @@ -1720,18 +1723,18 @@ func ErrorsEqual(t *testing.T, actual, expected error) { t.Errorf("expected error %s but received nil", expected.Error()) } - if influxdb.ErrorCode(expected) != influxdb.ErrorCode(actual) { + if errors.ErrorCode(expected) != errors.ErrorCode(actual) { t.Logf("\nexpected: %v\nactual: %v\n\n", expected, actual) - t.Errorf("expected error code %q but received %q", influxdb.ErrorCode(expected), influxdb.ErrorCode(actual)) + t.Errorf("expected error code %q but received %q", errors.ErrorCode(expected), errors.ErrorCode(actual)) } - if influxdb.ErrorMessage(expected) != influxdb.ErrorMessage(actual) { + if errors.ErrorMessage(expected) != errors.ErrorMessage(actual) { t.Logf("\nexpected: %v\nactual: %v\n\n", expected, actual) - t.Errorf("expected error message %q but received %q", influxdb.ErrorMessage(expected), influxdb.ErrorMessage(actual)) + t.Errorf("expected error message %q but received %q", errors.ErrorMessage(expected), errors.ErrorMessage(actual)) } } -func influxErrsEqual(t *testing.T, expected *influxdb.Error, actual error) { +func influxErrsEqual(t *testing.T, expected *errors.Error, actual error) { t.Helper() if expected != nil { @@ -1746,7 +1749,7 @@ func influxErrsEqual(t *testing.T, expected *influxdb.Error, actual error) { require.NoError(t, actual) return } - iErr, ok := actual.(*influxdb.Error) + iErr, ok := actual.(*errors.Error) require.True(t, ok) assert.Equal(t, expected.Code, iErr.Code) assert.Truef(t, strings.HasPrefix(iErr.Error(), expected.Error()), "expected: %s got err: %s", expected.Error(), actual.Error()) diff --git a/cmd/chronograf-migrator/dashboard.go b/cmd/chronograf-migrator/dashboard.go index cb4f693da41..9002b9c8965 100644 --- a/cmd/chronograf-migrator/dashboard.go +++ b/cmd/chronograf-migrator/dashboard.go @@ -8,6 +8,8 @@ import ( "strings" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/flux/ast" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/chronograf" @@ -379,7 +381,7 @@ func convertQueries(qs []chronograf.DashboardQuery) []influxdb.DashboardQuery { type dbrpMapper struct{} // FindBy returns the dbrp mapping for the specified ID. -func (d dbrpMapper) FindByID(ctx context.Context, orgID influxdb.ID, id influxdb.ID) (*influxdb.DBRPMappingV2, error) { +func (d dbrpMapper) FindByID(ctx context.Context, orgID platform.ID, id platform.ID) (*influxdb.DBRPMappingV2, error) { return nil, errors.New("mapping not found") } @@ -399,6 +401,6 @@ func (d dbrpMapper) Update(ctx context.Context, dbrp *influxdb.DBRPMappingV2) er } // Delete removes a dbrp mapping. -func (d dbrpMapper) Delete(ctx context.Context, orgID influxdb.ID, id influxdb.ID) error { +func (d dbrpMapper) Delete(ctx context.Context, orgID platform.ID, id platform.ID) error { return errors.New("dbrpMapper does not support deleting mappings") } diff --git a/cmd/influx/authorization.go b/cmd/influx/authorization.go index 6ef46e419b6..0bd5cb931aa 100644 --- a/cmd/influx/authorization.go +++ b/cmd/influx/authorization.go @@ -4,6 +4,8 @@ import ( "context" "io" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/authorization" "github.com/influxdata/influxdb/v2/cmd/influx/internal" @@ -11,13 +13,13 @@ import ( ) type token struct { - ID platform.ID `json:"id"` - Description string `json:"description"` - Token string `json:"token"` - Status string `json:"status"` - UserName string `json:"userName"` - UserID platform.ID `json:"userID"` - Permissions []string `json:"permissions"` + ID platform2.ID `json:"id"` + Description string `json:"description"` + Token string `json:"token"` + Status string `json:"status"` + UserName string `json:"userName"` + UserID platform2.ID `json:"userID"` + Permissions []string `json:"permissions"` } func cmdAuth(f *globalFlags, opt genericCLIOpts) *cobra.Command { @@ -163,7 +165,7 @@ func authorizationCreateF(cmd *cobra.Command, args []string) error { var permissions []platform.Permission for _, bp := range bucketPerms { for _, p := range bp.perms { - var id platform.ID + var id platform2.ID if err := id.DecodeFromString(p); err != nil { return err } @@ -340,7 +342,7 @@ func authorizationFindF(cmd *cobra.Command, args []string) error { var filter platform.AuthorizationFilter if authCRUDFlags.id != "" { - fID, err := platform.IDFromString(authCRUDFlags.id) + fID, err := platform2.IDFromString(authCRUDFlags.id) if err != nil { return err } @@ -350,7 +352,7 @@ func authorizationFindF(cmd *cobra.Command, args []string) error { filter.User = &authorizationFindFlags.user } if authorizationFindFlags.userID != "" { - uID, err := platform.IDFromString(authorizationFindFlags.userID) + uID, err := platform2.IDFromString(authorizationFindFlags.userID) if err != nil { return err } @@ -360,7 +362,7 @@ func authorizationFindF(cmd *cobra.Command, args []string) error { filter.Org = &authorizationFindFlags.org.name } if authorizationFindFlags.org.id != "" { - oID, err := platform.IDFromString(authorizationFindFlags.org.id) + oID, err := platform2.IDFromString(authorizationFindFlags.org.id) if err != nil { return err } @@ -428,7 +430,7 @@ func authorizationDeleteF(cmd *cobra.Command, args []string) error { return err } - id, err := platform.IDFromString(authCRUDFlags.id) + id, err := platform2.IDFromString(authCRUDFlags.id) if err != nil { return err } @@ -495,7 +497,7 @@ func authorizationActiveF(cmd *cobra.Command, args []string) error { return err } - var id platform.ID + var id platform2.ID if err := id.DecodeFromString(authCRUDFlags.id); err != nil { return err } @@ -563,7 +565,7 @@ func authorizationInactiveF(cmd *cobra.Command, args []string) error { return err } - var id platform.ID + var id platform2.ID if err := id.DecodeFromString(authCRUDFlags.id); err != nil { return err } diff --git a/cmd/influx/backup.go b/cmd/influx/backup.go index 23a8e963248..9e294d996db 100644 --- a/cmd/influx/backup.go +++ b/cmd/influx/backup.go @@ -4,7 +4,8 @@ import ( "context" "fmt" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/backup" "github.com/influxdata/influxdb/v2/http" influxlogger "github.com/influxdata/influxdb/v2/logger" @@ -73,14 +74,14 @@ func (b *cmdBackupBuilder) backupRunE(cmd *cobra.Command, _ []string) error { InsecureSkipVerify: flags.skipVerify, } - var orgID influxdb.ID + var orgID platform.ID if b.org.id != "" { if err := orgID.DecodeFromString(b.org.id); err != nil { return err } } - var bucketID influxdb.ID + var bucketID platform.ID if b.bucketID != "" { if err := bucketID.DecodeFromString(b.bucketID); err != nil { return err diff --git a/cmd/influx/bucket.go b/cmd/influx/bucket.go index a7125db45dd..570cb771e65 100644 --- a/cmd/influx/bucket.go +++ b/cmd/influx/bucket.go @@ -4,6 +4,8 @@ import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/cmd/internal" "github.com/influxdata/influxdb/v2/tenant" @@ -138,7 +140,7 @@ func (b *cmdBucketBuilder) cmdDeleteRunEFn(cmd *cobra.Command, args []string) er return err } - var id influxdb.ID + var id platform.ID var filter influxdb.BucketFilter if b.id == "" && b.name != "" { if err = b.org.validOrgFlags(&flags); err != nil { @@ -146,7 +148,7 @@ func (b *cmdBucketBuilder) cmdDeleteRunEFn(cmd *cobra.Command, args []string) er } filter.Name = &b.name if b.org.id != "" { - if filter.OrganizationID, err = influxdb.IDFromString(b.org.id); err != nil { + if filter.OrganizationID, err = platform.IDFromString(b.org.id); err != nil { return err } } else if b.org.name != "" { @@ -213,14 +215,14 @@ func (b *cmdBucketBuilder) cmdListRunEFn(cmd *cobra.Command, args []string) erro filter.Name = &b.name } if b.id != "" { - id, err := influxdb.IDFromString(b.id) + id, err := platform.IDFromString(b.id) if err != nil { return fmt.Errorf("failed to decode bucket id %q: %v", b.id, err) } filter.ID = id } if b.org.id != "" { - orgID, err := influxdb.IDFromString(b.org.id) + orgID, err := platform.IDFromString(b.org.id) if err != nil { return fmt.Errorf("failed to decode org id %q: %v", b.org.id, err) } @@ -272,7 +274,7 @@ func (b *cmdBucketBuilder) cmdUpdateRunEFn(cmd *cobra.Command, args []string) er return err } - var id influxdb.ID + var id platform.ID if err := id.DecodeFromString(b.id); err != nil { return fmt.Errorf("failed to decode bucket id %q: %v", b.id, err) } diff --git a/cmd/influx/bucket_test.go b/cmd/influx/bucket_test.go index 01988c3c7cc..03b743ffc4b 100644 --- a/cmd/influx/bucket_test.go +++ b/cmd/influx/bucket_test.go @@ -10,6 +10,8 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" "github.com/spf13/cobra" @@ -18,7 +20,7 @@ import ( ) func TestCmdBucket(t *testing.T) { - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) fakeSVCFn := func(svc influxdb.BucketService) bucketSVCsFn { return func() (influxdb.BucketService, influxdb.OrganizationService, error) { @@ -142,39 +144,39 @@ func TestCmdBucket(t *testing.T) { t.Run("delete", func(t *testing.T) { tests := []struct { name string - expectedID influxdb.ID + expectedID platform.ID flags []string }{ { name: "with description and retention period", - expectedID: influxdb.ID(1), - flags: []string{"--id=" + influxdb.ID(1).String()}, + expectedID: platform.ID(1), + flags: []string{"--id=" + platform.ID(1).String()}, }, { name: "shorts", - expectedID: influxdb.ID(1), - flags: []string{"-i=" + influxdb.ID(1).String()}, + expectedID: platform.ID(1), + flags: []string{"-i=" + platform.ID(1).String()}, }, { name: "with name and org name", - expectedID: influxdb.ID(1), + expectedID: platform.ID(1), flags: []string{"--name=n1", "--org=org1"}, }, { name: "with name and org name short", - expectedID: influxdb.ID(1), + expectedID: platform.ID(1), flags: []string{"-n=n1", "-o=org1"}, }, { name: "with name and org id", - expectedID: influxdb.ID(1), - flags: []string{"--name=n1", "--org-id=" + influxdb.ID(3).String()}, + expectedID: platform.ID(1), + flags: []string{"--name=n1", "--org-id=" + platform.ID(3).String()}, }, } - cmdFn := func(expectedID influxdb.ID) func(*globalFlags, genericCLIOpts) *cobra.Command { + cmdFn := func(expectedID platform.ID) func(*globalFlags, genericCLIOpts) *cobra.Command { svc := mock.NewBucketService() - svc.FindBucketByIDFn = func(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + svc.FindBucketByIDFn = func(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ID: id}, nil } svc.FindBucketFn = func(ctx context.Context, filter influxdb.BucketFilter) (*influxdb.Bucket, error) { @@ -186,7 +188,7 @@ func TestCmdBucket(t *testing.T) { } return nil, nil } - svc.DeleteBucketFn = func(ctx context.Context, id influxdb.ID) error { + svc.DeleteBucketFn = func(ctx context.Context, id platform.ID) error { if expectedID != id { return fmt.Errorf("unexpected id:\n\twant= %s\n\tgot= %s", expectedID, id) } @@ -226,8 +228,8 @@ func TestCmdBucket(t *testing.T) { t.Run("list", func(t *testing.T) { type called struct { name string - id influxdb.ID - orgID influxdb.ID + id platform.ID + orgID platform.ID org string } @@ -240,15 +242,15 @@ func TestCmdBucket(t *testing.T) { }{ { name: "org id", - flags: []string{"--org-id=" + influxdb.ID(3).String()}, + flags: []string{"--org-id=" + platform.ID(3).String()}, envVars: envVarsZeroMap, expected: called{orgID: 3}, }, { name: "id", flags: []string{ - "--id=" + influxdb.ID(2).String(), - "--org-id=" + influxdb.ID(3).String(), + "--id=" + platform.ID(2).String(), + "--org-id=" + platform.ID(3).String(), }, envVars: envVarsZeroMap, expected: called{ @@ -273,7 +275,7 @@ func TestCmdBucket(t *testing.T) { flags: []string{ "-o=rg", "-n=name1", - "-i=" + influxdb.ID(1).String(), + "-i=" + platform.ID(1).String(), }, envVars: envVarsZeroMap, expected: called{org: "rg", name: "name1", id: 1}, @@ -284,31 +286,31 @@ func TestCmdBucket(t *testing.T) { "INFLUX_ORG": "rg", "INFLUX_BUCKET_NAME": "name1", }, - flags: []string{"-i=" + influxdb.ID(1).String()}, + flags: []string{"-i=" + platform.ID(1).String()}, expected: called{org: "rg", name: "name1", id: 1}, }, { name: "env vars 2", envVars: map[string]string{ "INFLUX_ORG": "", - "INFLUX_ORG_ID": influxdb.ID(2).String(), + "INFLUX_ORG_ID": platform.ID(2).String(), "INFLUX_BUCKET_NAME": "name1", }, - flags: []string{"-i=" + influxdb.ID(1).String()}, + flags: []string{"-i=" + platform.ID(1).String()}, expected: called{orgID: 2, name: "name1", id: 1}, }, { name: "ls alias", command: "ls", envVars: envVarsZeroMap, - flags: []string{"--org-id=" + influxdb.ID(3).String()}, + flags: []string{"--org-id=" + platform.ID(3).String()}, expected: called{orgID: 3}, }, { name: "find alias", command: "find", envVars: envVarsZeroMap, - flags: []string{"--org-id=" + influxdb.ID(3).String()}, + flags: []string{"--org-id=" + platform.ID(3).String()}, expected: called{orgID: 3}, }, } @@ -374,7 +376,7 @@ func TestCmdBucket(t *testing.T) { { name: "basic just name", flags: []string{ - "--id=" + influxdb.ID(3).String(), + "--id=" + platform.ID(3).String(), "--name=new name", }, expected: influxdb.BucketUpdate{ @@ -384,7 +386,7 @@ func TestCmdBucket(t *testing.T) { { name: "with all fields", flags: []string{ - "--id=" + influxdb.ID(3).String(), + "--id=" + platform.ID(3).String(), "--name=new name", "--description=desc", "--retention=1m", @@ -398,7 +400,7 @@ func TestCmdBucket(t *testing.T) { { name: "shorts", flags: []string{ - "-i=" + influxdb.ID(3).String(), + "-i=" + platform.ID(3).String(), "-n=new name", "-d=desc", "-r=1m", @@ -412,7 +414,7 @@ func TestCmdBucket(t *testing.T) { { name: "env var", flags: []string{ - "-i=" + influxdb.ID(3).String(), + "-i=" + platform.ID(3).String(), "-d=desc", "-r=1m", }, @@ -426,7 +428,7 @@ func TestCmdBucket(t *testing.T) { { name: "shard-group duration", flags: []string{ - "-i=" + influxdb.ID(3).String(), + "-i=" + platform.ID(3).String(), "--shard-group-duration=1m", }, expected: influxdb.BucketUpdate{ @@ -437,9 +439,9 @@ func TestCmdBucket(t *testing.T) { cmdFn := func(expectedUpdate influxdb.BucketUpdate) func(*globalFlags, genericCLIOpts) *cobra.Command { svc := mock.NewBucketService() - svc.UpdateBucketFn = func(ctx context.Context, id influxdb.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { + svc.UpdateBucketFn = func(ctx context.Context, id platform.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { if id != 3 { - return nil, fmt.Errorf("unexpecte id:\n\twant= %s\n\tgot= %s", influxdb.ID(3), id) + return nil, fmt.Errorf("unexpecte id:\n\twant= %s\n\tgot= %s", platform.ID(3), id) } if !reflect.DeepEqual(expectedUpdate, upd) { return nil, fmt.Errorf("unexpected bucket update;\n\twant= %+v\n\tgot= %+v", expectedUpdate, upd) diff --git a/cmd/influx/config.go b/cmd/influx/config.go index 8466194ac25..33c1eb965fa 100644 --- a/cmd/influx/config.go +++ b/cmd/influx/config.go @@ -5,7 +5,8 @@ import ( "net/url" "path/filepath" - "github.com/influxdata/influxdb/v2" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2/cmd/influx/config" "github.com/spf13/cobra" ) @@ -198,7 +199,7 @@ func (b *cmdConfigBuilder) cmdDeleteRunEFn(cmd *cobra.Command, args []string) er } cfg, err := svc.DeleteConfig(name) - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors2.ErrorCode(err) == errors2.ENotFound { continue } if err != nil { diff --git a/cmd/influx/config/config.go b/cmd/influx/config/config.go index d78895b923d..451143e3ab8 100644 --- a/cmd/influx/config/config.go +++ b/cmd/influx/config/config.go @@ -8,8 +8,9 @@ import ( "io/ioutil" "os" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/BurntSushi/toml" - "github.com/influxdata/influxdb/v2" ) // Config store the crendentials of influxdb host and token. @@ -52,8 +53,8 @@ type store interface { // Switch to another config. func (cfgs Configs) Switch(name string) error { if _, ok := cfgs[name]; !ok { - return &influxdb.Error{ - Code: influxdb.ENotFound, + return &errors.Error{ + Code: errors.ENotFound, Msg: fmt.Sprintf(`config %q is not found`, name), } } @@ -135,8 +136,8 @@ var badNames = map[string]bool{ func blockBadName(cfgs Configs) error { for n := range cfgs { if _, ok := badNames[n]; ok { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf(`%q is not a valid config name`, n), } } @@ -194,8 +195,8 @@ func (s baseRW) ListConfigs() (Configs, error) { // CreateConfig create new config. func (svc localConfigsSVC) CreateConfig(cfg Config) (Config, error) { if cfg.Name == "" { - return Config{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return Config{}, &errors.Error{ + Code: errors.EInvalid, Msg: "config name is empty", } } @@ -204,8 +205,8 @@ func (svc localConfigsSVC) CreateConfig(cfg Config) (Config, error) { return Config{}, err } if _, ok := cfgs[cfg.Name]; ok { - return Config{}, &influxdb.Error{ - Code: influxdb.EConflict, + return Config{}, &errors.Error{ + Code: errors.EConflict, Msg: fmt.Sprintf("config %q already exists", cfg.Name), } } @@ -228,8 +229,8 @@ func (svc localConfigsSVC) DeleteConfig(name string) (Config, error) { p, ok := cfgs[name] if !ok { - return Config{}, &influxdb.Error{ - Code: influxdb.ENotFound, + return Config{}, &errors.Error{ + Code: errors.ENotFound, Msg: fmt.Sprintf("config %q is not found", name), } } @@ -270,8 +271,8 @@ func (svc localConfigsSVC) UpdateConfig(up Config) (Config, error) { } p0, ok := cfgs[up.Name] if !ok { - return Config{}, &influxdb.Error{ - Code: influxdb.ENotFound, + return Config{}, &errors.Error{ + Code: errors.ENotFound, Msg: fmt.Sprintf("config %q is not found", up.Name), } } @@ -337,8 +338,8 @@ func (s baseRW) parseActiveConfig(currentOrPrevious bool) (Config, error) { activated = cfg hasActive = true } else if check { - return DefaultConfig, &influxdb.Error{ - Code: influxdb.EConflict, + return DefaultConfig, &errors.Error{ + Code: errors.EConflict, Msg: "more than one " + previousText + "activated configs found", } } @@ -346,8 +347,8 @@ func (s baseRW) parseActiveConfig(currentOrPrevious bool) (Config, error) { if hasActive { return activated, nil } - return DefaultConfig, &influxdb.Error{ - Code: influxdb.ENotFound, + return DefaultConfig, &errors.Error{ + Code: errors.ENotFound, Msg: previousText + "activated config is not found", } } diff --git a/cmd/influx/config/config_test.go b/cmd/influx/config/config_test.go index cf822ab9faa..a522b479cef 100644 --- a/cmd/influx/config/config_test.go +++ b/cmd/influx/config/config_test.go @@ -4,29 +4,30 @@ import ( "bytes" "testing" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" - "github.com/influxdata/influxdb/v2" influxtesting "github.com/influxdata/influxdb/v2/testing" ) func TestWriteConfigs(t *testing.T) { cases := []struct { name string - err *influxdb.Error + err *errors.Error pp Configs result string }{ { name: "bad name -", - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: `"-" is not a valid config name`, }, }, { name: "bad name create", - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: `"create" is not a valid config name`, }, }, @@ -259,8 +260,8 @@ func TestConfigsSwith(t *testing.T) { "a1": {Host: "host1"}, "a2": {Host: "host2"}, }, - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: `config "p1" is not found`, }, }, @@ -315,8 +316,8 @@ func TestConfigCreate(t *testing.T) { }{ { name: "invalid name", - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "config name is empty", }, }, @@ -381,8 +382,8 @@ func TestConfigCreate(t *testing.T) { Name: "default", Host: "host1", }, - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Msg: `config "default" already exists`, }, }, @@ -460,16 +461,16 @@ func TestConfigSwitch(t *testing.T) { }{ { name: "empty", - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: `config "" is not found`, }, }, { name: "not found", src: "default", - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: `config "default" is not found`, }, }, @@ -576,8 +577,8 @@ func TestConfigSwitch(t *testing.T) { }, }, src: "-", - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "previous activated config is not found", }, }, @@ -613,8 +614,8 @@ func TestConfigUpdate(t *testing.T) { }{ { name: "empty", - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: `config "" is not found`, }, }, @@ -626,8 +627,8 @@ func TestConfigUpdate(t *testing.T) { Org: "org1", Token: "tok1", }, - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: `config "default" is not found`, }, }, @@ -711,8 +712,8 @@ func TestConfigDelete(t *testing.T) { }{ { name: "empty", - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: `config "" is not found`, }, }, @@ -725,8 +726,8 @@ func TestConfigDelete(t *testing.T) { Host: "host1", }, }, - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: `config "bad" is not found`, }, }, diff --git a/cmd/influx/config_test.go b/cmd/influx/config_test.go index 647deb16779..f6e0064e844 100644 --- a/cmd/influx/config_test.go +++ b/cmd/influx/config_test.go @@ -8,8 +8,9 @@ import ( "path/filepath" "testing" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/cmd/influx/config" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" @@ -96,7 +97,7 @@ func TestCmdConfig(t *testing.T) { return &mockConfigService{ CreateConfigFn: func(cfg config.Config) (config.Config, error) { if diff := cmp.Diff(expected, cfg); diff != "" { - return config.Config{}, &influxdb.Error{ + return config.Config{}, &errors.Error{ Msg: fmt.Sprintf("create config failed, diff %s", diff), } } @@ -255,7 +256,7 @@ func TestCmdConfig(t *testing.T) { cfg.Active = true cfg.PreviousActive = false if diff := cmp.Diff(expected, cfg); diff != "" { - return config.Config{}, &influxdb.Error{ + return config.Config{}, &errors.Error{ Msg: fmt.Sprintf("switch config failed, diff %s", diff), } } @@ -380,7 +381,7 @@ func TestCmdConfig(t *testing.T) { return &mockConfigService{ UpdateConfigFn: func(cfg config.Config) (config.Config, error) { if diff := cmp.Diff(expected, cfg); diff != "" { - return config.Config{}, &influxdb.Error{ + return config.Config{}, &errors.Error{ Msg: fmt.Sprintf("update config failed, diff %s", diff), } } @@ -496,7 +497,7 @@ func TestCmdConfig(t *testing.T) { } } if diff := cmp.Diff(expected, cfg); diff != "" { - return config.Config{}, &influxdb.Error{ + return config.Config{}, &errors.Error{ Msg: fmt.Sprintf("delete config failed, diff %s", diff), } } diff --git a/cmd/influx/dashboard.go b/cmd/influx/dashboard.go index df6368b56ab..d2b6f118031 100644 --- a/cmd/influx/dashboard.go +++ b/cmd/influx/dashboard.go @@ -3,6 +3,9 @@ package main import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/cmd/influx/internal" "github.com/influxdata/influxdb/v2/dashboards/transport" @@ -65,15 +68,15 @@ func (b *cmdDashboardBuilder) listRunE(cmd *cobra.Command, args []string) error orgID, _ := b.org.getID(orgSVC) if orgID == 0 && len(b.ids) == 0 { - return &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + return &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: "at least one of org, org-id, or id must be provided", } } - var ids []*influxdb.ID + var ids []*platform.ID for _, rawID := range b.ids { - id, err := influxdb.IDFromString(rawID) + id, err := platform.IDFromString(rawID) if err != nil { return err } @@ -93,7 +96,7 @@ func (b *cmdDashboardBuilder) listRunE(cmd *cobra.Command, args []string) error Limit: limit, Offset: offset, }) - if err != nil && influxdb.ErrorCode(err) != influxdb.ENotFound { + if err != nil && errors.ErrorCode(err) != errors.ENotFound { return err } out = append(out, dashboards...) diff --git a/cmd/influx/internal/tabwriter.go b/cmd/influx/internal/tabwriter.go index aeee4226ce0..514e0152c2e 100644 --- a/cmd/influx/internal/tabwriter.go +++ b/cmd/influx/internal/tabwriter.go @@ -6,7 +6,7 @@ import ( "strings" "text/tabwriter" - platform "github.com/influxdata/influxdb/v2" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" ) // TabWriter wraps tab writer headers logic. @@ -62,7 +62,7 @@ func formatStringType(i interface{}) string { switch i.(type) { case int: return "%d" - case platform.ID, string: + case platform2.ID, string: return "%s" } diff --git a/cmd/influx/main.go b/cmd/influx/main.go index 01d1cdb5f84..1bdb2fa4b75 100644 --- a/cmd/influx/main.go +++ b/cmd/influx/main.go @@ -13,6 +13,9 @@ import ( "sync" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/cmd/influx/config" "github.com/influxdata/influxdb/v2/cmd/influx/internal" @@ -469,7 +472,7 @@ func checkSetupRunEMiddleware(f *globalFlags) cobraRunEMiddleware { } ac := f.config() - if setupErr := checkSetup(ac.Host, f.skipVerify); setupErr != nil && influxdb.EUnauthorized != influxdb.ErrorCode(setupErr) { + if setupErr := checkSetup(ac.Host, f.skipVerify); setupErr != nil && errors.EUnauthorized != errors.ErrorCode(setupErr) { cmd.OutOrStderr().Write([]byte(fmt.Sprintf("Error: %s\n", internal.ErrorFmt(err).Error()))) return internal.ErrorFmt(setupErr) } @@ -510,16 +513,16 @@ func (o *organization) register(v *viper.Viper, cmd *cobra.Command, persistent b opts.mustRegister(v, cmd) } -func (o *organization) getID(orgSVC influxdb.OrganizationService) (influxdb.ID, error) { +func (o *organization) getID(orgSVC influxdb.OrganizationService) (platform.ID, error) { if o.id != "" { - influxOrgID, err := influxdb.IDFromString(o.id) + influxOrgID, err := platform.IDFromString(o.id) if err != nil { return 0, fmt.Errorf("invalid org ID '%s' provided (did you pass an org name instead of an ID?): %w", o.id, err) } return *influxOrgID, nil } - getOrgByName := func(name string) (influxdb.ID, error) { + getOrgByName := func(name string) (platform.ID, error) { org, err := orgSVC.FindOrganization(context.Background(), influxdb.OrganizationFilter{ Name: &name, }) diff --git a/cmd/influx/organization.go b/cmd/influx/organization.go index 4d2927b36ca..3cad96e18f1 100644 --- a/cmd/influx/organization.go +++ b/cmd/influx/organization.go @@ -5,6 +5,9 @@ import ( "fmt" "io" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/tenant" "github.com/spf13/cobra" @@ -111,7 +114,7 @@ func (b *cmdOrgBuilder) deleteRunEFn(cmd *cobra.Command, args []string) error { return fmt.Errorf("failed to initialize org service client: %v", err) } - var id influxdb.ID + var id platform.ID if err := id.DecodeFromString(b.id); err != nil { return fmt.Errorf("failed to decode org id %s: %v", b.id, err) } @@ -171,7 +174,7 @@ func (b *cmdOrgBuilder) findRunEFn(cmd *cobra.Command, args []string) error { } if b.id != "" { - id, err := influxdb.IDFromString(b.id) + id, err := platform.IDFromString(b.id) if err != nil { return fmt.Errorf("failed to decode org id %s: %v", b.id, err) } @@ -226,7 +229,7 @@ func (b *cmdOrgBuilder) updateRunEFn(cmd *cobra.Command, args []string) error { return fmt.Errorf("failed to initialize org service client: %v", err) } - var id influxdb.ID + var id platform.ID if err := id.DecodeFromString(b.id); err != nil { return fmt.Errorf("failed to decode org id %s: %v", b.id, err) } @@ -341,7 +344,7 @@ func (b *cmdOrgBuilder) memberListRunEFn(cmd *cobra.Command, args []string) erro } if b.id != "" { - var fID influxdb.ID + var fID platform.ID err := fID.DecodeFromString(b.id) if err != nil { return fmt.Errorf("failed to decode org id %s: %v", b.id, err) @@ -409,7 +412,7 @@ func (b *cmdOrgBuilder) memberAddRunEFn(cmd *cobra.Command, args []string) error } if b.id != "" { - var fID influxdb.ID + var fID platform.ID err := fID.DecodeFromString(b.id) if err != nil { return fmt.Errorf("failed to decode org id %s: %v", b.id, err) @@ -423,7 +426,7 @@ func (b *cmdOrgBuilder) memberAddRunEFn(cmd *cobra.Command, args []string) error return fmt.Errorf("failed to find org: %v", err) } - var memberID influxdb.ID + var memberID platform.ID err = memberID.DecodeFromString(b.memberID) if err != nil { return fmt.Errorf("failed to decode member id %s: %v", b.memberID, err) @@ -486,7 +489,7 @@ func (b *cmdOrgBuilder) membersRemoveRunEFn(cmd *cobra.Command, args []string) e } if b.id != "" { - var fID influxdb.ID + var fID platform.ID err := fID.DecodeFromString(b.id) if err != nil { return fmt.Errorf("failed to decode org id %s: %v", b.id, err) @@ -500,7 +503,7 @@ func (b *cmdOrgBuilder) membersRemoveRunEFn(cmd *cobra.Command, args []string) e return fmt.Errorf("failed to find organization: %v", err) } - var memberID influxdb.ID + var memberID platform.ID err = memberID.DecodeFromString(b.memberID) if err != nil { return fmt.Errorf("failed to decode member id %s: %v", b.memberID, err) @@ -580,7 +583,7 @@ func (b *cmdOrgBuilder) memberList(ctx context.Context, urmSVC influxdb.UserReso for i := 0; i < len(mappings); i++ { select { case <-ctx.Done(): - return &influxdb.Error{ + return &errors.Error{ Msg: "Timeout retrieving user details", } case err := <-errC: @@ -620,7 +623,7 @@ func addMember(ctx context.Context, w io.Writer, urmSVC influxdb.UserResourceMap return err } -func removeMember(ctx context.Context, w io.Writer, urmSVC influxdb.UserResourceMappingService, resourceID, userID influxdb.ID) error { +func removeMember(ctx context.Context, w io.Writer, urmSVC influxdb.UserResourceMappingService, resourceID, userID platform.ID) error { if err := urmSVC.DeleteUserResourceMapping(ctx, resourceID, userID); err != nil { return fmt.Errorf("failed to remove member: %v", err) } diff --git a/cmd/influx/organization_test.go b/cmd/influx/organization_test.go index 036c47b6cd1..fdf4222ada9 100644 --- a/cmd/influx/organization_test.go +++ b/cmd/influx/organization_test.go @@ -8,6 +8,8 @@ import ( "reflect" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/stretchr/testify/assert" "github.com/influxdata/influxdb/v2" @@ -87,27 +89,27 @@ func TestCmdOrg(t *testing.T) { t.Run("delete", func(t *testing.T) { tests := []struct { name string - expectedID influxdb.ID + expectedID platform.ID flag string }{ { name: "id", - expectedID: influxdb.ID(1), + expectedID: platform.ID(1), flag: "--id=", }, { name: "shorts", - expectedID: influxdb.ID(1), + expectedID: platform.ID(1), flag: "-i=", }, } - cmdFn := func(expectedID influxdb.ID) func(*globalFlags, genericCLIOpts) *cobra.Command { + cmdFn := func(expectedID platform.ID) func(*globalFlags, genericCLIOpts) *cobra.Command { svc := mock.NewOrganizationService() - svc.FindOrganizationByIDF = func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + svc.FindOrganizationByIDF = func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ID: id}, nil } - svc.DeleteOrganizationF = func(ctx context.Context, id influxdb.ID) error { + svc.DeleteOrganizationF = func(ctx context.Context, id platform.ID) error { if expectedID != id { return fmt.Errorf("unexpected id:\n\twant= %s\n\tgot= %s", expectedID, id) } @@ -140,7 +142,7 @@ func TestCmdOrg(t *testing.T) { t.Run("list", func(t *testing.T) { type called struct { name string - id influxdb.ID + id platform.ID } tests := []struct { @@ -152,7 +154,7 @@ func TestCmdOrg(t *testing.T) { }{ { name: "org id", - flags: []string{"--id=" + influxdb.ID(3).String()}, + flags: []string{"--id=" + platform.ID(3).String()}, envVars: envVarsZeroMap, expected: called{id: 3}, }, @@ -166,7 +168,7 @@ func TestCmdOrg(t *testing.T) { name: "shorts", flags: []string{ "-n=name1", - "-i=" + influxdb.ID(1).String(), + "-i=" + platform.ID(1).String(), }, envVars: envVarsZeroMap, expected: called{name: "name1", id: 1}, @@ -174,10 +176,10 @@ func TestCmdOrg(t *testing.T) { { name: "env vars", envVars: map[string]string{ - "INFLUX_ORG_ID": influxdb.ID(1).String(), + "INFLUX_ORG_ID": platform.ID(1).String(), "INFLUX_ORG": "name1", }, - flags: []string{"-i=" + influxdb.ID(1).String()}, + flags: []string{"-i=" + platform.ID(1).String()}, expected: called{name: "name1", id: 1}, }, { @@ -251,7 +253,7 @@ func TestCmdOrg(t *testing.T) { { name: "basic just name", flags: []string{ - "--id=" + influxdb.ID(3).String(), + "--id=" + platform.ID(3).String(), "--name=new name", }, expected: influxdb.OrganizationUpdate{ @@ -261,7 +263,7 @@ func TestCmdOrg(t *testing.T) { { name: "with all fields", flags: []string{ - "--id=" + influxdb.ID(3).String(), + "--id=" + platform.ID(3).String(), "--name=new name", "--description=desc", }, @@ -273,7 +275,7 @@ func TestCmdOrg(t *testing.T) { { name: "shorts", flags: []string{ - "-i=" + influxdb.ID(3).String(), + "-i=" + platform.ID(3).String(), "-n=new name", "-d=desc", }, @@ -286,7 +288,7 @@ func TestCmdOrg(t *testing.T) { name: "env var", envVars: map[string]string{ "INFLUX_ORG": "new name", - "INFLUX_ORG_ID": influxdb.ID(3).String(), + "INFLUX_ORG_ID": platform.ID(3).String(), "INFLUX_ORG_DESCRIPTION": "desc", }, expected: influxdb.OrganizationUpdate{ @@ -298,9 +300,9 @@ func TestCmdOrg(t *testing.T) { cmdFn := func(expectedUpdate influxdb.OrganizationUpdate) func(*globalFlags, genericCLIOpts) *cobra.Command { svc := mock.NewOrganizationService() - svc.UpdateOrganizationF = func(ctx context.Context, id influxdb.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { + svc.UpdateOrganizationF = func(ctx context.Context, id platform.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { if id != 3 { - return nil, fmt.Errorf("unexpecte id:\n\twant= %s\n\tgot= %s", influxdb.ID(3), id) + return nil, fmt.Errorf("unexpecte id:\n\twant= %s\n\tgot= %s", platform.ID(3), id) } if !reflect.DeepEqual(expectedUpdate, upd) { return nil, fmt.Errorf("unexpected bucket update;\n\twant= %+v\n\tgot= %+v", expectedUpdate, upd) @@ -336,8 +338,8 @@ func TestCmdOrg(t *testing.T) { type ( called struct { name string - id influxdb.ID - memberID influxdb.ID + id platform.ID + memberID platform.ID } testCase struct { @@ -384,13 +386,13 @@ func TestCmdOrg(t *testing.T) { tests := []testCase{ { name: "org id", - memberFlags: []string{"--id=" + influxdb.ID(3).String()}, + memberFlags: []string{"--id=" + platform.ID(3).String()}, envVars: envVarsZeroMap, expected: called{id: 3}, }, { name: "org id short", - memberFlags: []string{"-i=" + influxdb.ID(3).String()}, + memberFlags: []string{"-i=" + platform.ID(3).String()}, envVars: envVarsZeroMap, expected: called{id: 3}, }, @@ -398,7 +400,7 @@ func TestCmdOrg(t *testing.T) { name: "org id env var", envVars: map[string]string{ "INFLUX_ORG": "", - "INFLUX_ORG_ID": influxdb.ID(3).String(), + "INFLUX_ORG_ID": platform.ID(3).String(), }, expected: called{id: 3}, }, @@ -476,8 +478,8 @@ func TestCmdOrg(t *testing.T) { { name: "org id", memberFlags: []string{ - "--id=" + influxdb.ID(3).String(), - "--member=" + influxdb.ID(4).String(), + "--id=" + platform.ID(3).String(), + "--member=" + platform.ID(4).String(), }, envVars: envVarsZeroMap, expected: called{id: 3, memberID: 4}, @@ -485,8 +487,8 @@ func TestCmdOrg(t *testing.T) { { name: "org id shorts", memberFlags: []string{ - "-i=" + influxdb.ID(3).String(), - "-m=" + influxdb.ID(4).String(), + "-i=" + platform.ID(3).String(), + "-m=" + platform.ID(4).String(), }, envVars: envVarsZeroMap, expected: called{id: 3, memberID: 4}, @@ -495,7 +497,7 @@ func TestCmdOrg(t *testing.T) { name: "org name", memberFlags: []string{ "--name=name1", - "--member=" + influxdb.ID(4).String(), + "--member=" + platform.ID(4).String(), }, envVars: envVarsZeroMap, expected: called{name: "name1", memberID: 4}, @@ -504,7 +506,7 @@ func TestCmdOrg(t *testing.T) { name: "org name shorts", memberFlags: []string{ "-n=name1", - "-m=" + influxdb.ID(4).String(), + "-m=" + platform.ID(4).String(), }, envVars: envVarsZeroMap, expected: called{name: "name1", memberID: 4}, @@ -529,7 +531,7 @@ func TestCmdOrg(t *testing.T) { return &influxdb.Organization{ID: 1}, nil } urmSVC := mock.NewUserResourceMappingService() - urmSVC.DeleteMappingFn = func(ctx context.Context, resourceID, userID influxdb.ID) error { + urmSVC.DeleteMappingFn = func(ctx context.Context, resourceID, userID platform.ID) error { calls.memberID = userID return nil } @@ -544,8 +546,8 @@ func TestCmdOrg(t *testing.T) { { name: "org id", memberFlags: []string{ - "--id=" + influxdb.ID(3).String(), - "--member=" + influxdb.ID(4).String(), + "--id=" + platform.ID(3).String(), + "--member=" + platform.ID(4).String(), }, envVars: envVarsZeroMap, expected: called{id: 3, memberID: 4}, @@ -553,8 +555,8 @@ func TestCmdOrg(t *testing.T) { { name: "org id shorts", memberFlags: []string{ - "-i=" + influxdb.ID(3).String(), - "-m=" + influxdb.ID(4).String(), + "-i=" + platform.ID(3).String(), + "-m=" + platform.ID(4).String(), }, envVars: envVarsZeroMap, expected: called{id: 3, memberID: 4}, @@ -563,7 +565,7 @@ func TestCmdOrg(t *testing.T) { name: "org name", memberFlags: []string{ "--name=name1", - "--member=" + influxdb.ID(4).String(), + "--member=" + platform.ID(4).String(), }, envVars: envVarsZeroMap, expected: called{name: "name1", memberID: 4}, @@ -572,7 +574,7 @@ func TestCmdOrg(t *testing.T) { name: "org name shorts", memberFlags: []string{ "-n=name1", - "-m=" + influxdb.ID(4).String(), + "-m=" + platform.ID(4).String(), }, envVars: envVarsZeroMap, expected: called{name: "name1", memberID: 4}, diff --git a/cmd/influx/restore.go b/cmd/influx/restore.go index 627eebc1f50..cf4132cbd62 100644 --- a/cmd/influx/restore.go +++ b/cmd/influx/restore.go @@ -5,7 +5,8 @@ import ( "fmt" "os" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/http" influxlogger "github.com/influxdata/influxdb/v2/logger" "github.com/influxdata/influxdb/v2/restore" @@ -98,14 +99,14 @@ func (b *cmdRestoreBuilder) restoreRunE(cmd *cobra.Command, args []string) (err BucketService: &tenant.BucketClientService{Client: client}, } - var orgID influxdb.ID + var orgID platform.ID if b.org.id != "" { if err := orgID.DecodeFromString(b.org.id); err != nil { return err } } - var bucketID influxdb.ID + var bucketID platform.ID if b.bucketID != "" { if err := bucketID.DecodeFromString(b.bucketID); err != nil { return err diff --git a/cmd/influx/secret.go b/cmd/influx/secret.go index 0d797f3c463..72b54106138 100644 --- a/cmd/influx/secret.go +++ b/cmd/influx/secret.go @@ -4,6 +4,8 @@ import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/cmd/internal" isecret "github.com/influxdata/influxdb/v2/secret" @@ -236,7 +238,7 @@ type ( secret struct { key string - orgID influxdb.ID + orgID platform.ID } ) diff --git a/cmd/influx/secret_test.go b/cmd/influx/secret_test.go index d19189e2c78..5943f2d4bdc 100644 --- a/cmd/influx/secret_test.go +++ b/cmd/influx/secret_test.go @@ -7,6 +7,8 @@ import ( "io/ioutil" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" "github.com/spf13/cobra" @@ -16,7 +18,7 @@ import ( ) func TestCmdSecret(t *testing.T) { - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) fakeSVCFn := func(svc influxdb.SecretService, fn func(*input.UI) string) secretSVCsFn { return func() (influxdb.SecretService, influxdb.OrganizationService, func(*input.UI) string, error) { @@ -39,7 +41,7 @@ func TestCmdSecret(t *testing.T) { }{ { name: "org id", - flags: []string{"--org-id=" + influxdb.ID(3).String()}, + flags: []string{"--org-id=" + platform.ID(3).String()}, envVars: envVarsZeroMap, expected: called{"k1", "k2", "k3"}, }, @@ -76,7 +78,7 @@ func TestCmdSecret(t *testing.T) { cmdFn := func() (func(*globalFlags, genericCLIOpts) *cobra.Command, *called) { calls := new(called) svc := mock.NewSecretService() - svc.GetSecretKeysFn = func(ctx context.Context, organizationID influxdb.ID) ([]string, error) { + svc.GetSecretKeysFn = func(ctx context.Context, organizationID platform.ID) ([]string, error) { if !organizationID.Valid() { return []string{}, nil } @@ -137,7 +139,7 @@ func TestCmdSecret(t *testing.T) { cmdFn := func(expectedKey string) func(*globalFlags, genericCLIOpts) *cobra.Command { svc := mock.NewSecretService() - svc.DeleteSecretFn = func(ctx context.Context, orgID influxdb.ID, ks ...string) error { + svc.DeleteSecretFn = func(ctx context.Context, orgID platform.ID, ks ...string) error { if expectedKey != ks[0] { return fmt.Errorf("unexpected id:\n\twant= %s\n\tgot= %s", expectedKey, ks[0]) } @@ -200,7 +202,7 @@ func TestCmdSecret(t *testing.T) { cmdFn := func(expectedKey string) func(*globalFlags, genericCLIOpts) *cobra.Command { svc := mock.NewSecretService() - svc.PatchSecretsFn = func(ctx context.Context, orgID influxdb.ID, m map[string]string) error { + svc.PatchSecretsFn = func(ctx context.Context, orgID platform.ID, m map[string]string) error { var key string for k := range m { key = k diff --git a/cmd/influx/task.go b/cmd/influx/task.go index 78537ee4033..744c591c19e 100644 --- a/cmd/influx/task.go +++ b/cmd/influx/task.go @@ -5,6 +5,8 @@ import ( "fmt" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/http" "github.com/influxdata/influxdb/v2/tenant" @@ -169,7 +171,7 @@ func (b *cmdTaskBuilder) taskFindF(cmd *cobra.Command, args []string) error { filter := influxdb.TaskFilter{} if b.taskFindFlags.user != "" { - id, err := influxdb.IDFromString(b.taskFindFlags.user) + id, err := platform.IDFromString(b.taskFindFlags.user) if err != nil { return err } @@ -180,7 +182,7 @@ func (b *cmdTaskBuilder) taskFindF(cmd *cobra.Command, args []string) error { filter.Organization = b.org.name } if b.org.id != "" { - id, err := influxdb.IDFromString(b.org.id) + id, err := platform.IDFromString(b.org.id) if err != nil { return err } @@ -195,7 +197,7 @@ func (b *cmdTaskBuilder) taskFindF(cmd *cobra.Command, args []string) error { var tasks []*influxdb.Task if b.taskID != "" { - id, err := influxdb.IDFromString(b.taskID) + id, err := platform.IDFromString(b.taskID) if err != nil { return err } @@ -282,7 +284,7 @@ func (b *cmdTaskBuilder) taskRetryFailedF(*cobra.Command, []string) error { } } if b.taskRerunFailedFlags.dryRun { - uniqueIDs := make(map[influxdb.ID]struct{}) + uniqueIDs := make(map[platform.ID]struct{}) for _, r := range failedRuns { uniqueIDs[r.TaskID] = struct{}{} } @@ -300,7 +302,7 @@ func (b *cmdTaskBuilder) getFailedRunsForTaskID(limit int) ([]*influxdb.Run, err return nil, err } runFilter := influxdb.RunFilter{Limit: limit} - id, err := influxdb.IDFromString(b.taskID) + id, err := platform.IDFromString(b.taskID) if err != nil { return nil, err } @@ -336,7 +338,7 @@ func (b *cmdTaskBuilder) getFailedRunsForOrg(taskLimit int, runLimit int) ([]*in taskFilter.Organization = b.org.name } if b.org.id != "" { - orgID, err := influxdb.IDFromString(b.org.id) + orgID, err := platform.IDFromString(b.org.id) if err != nil { return nil, err } @@ -392,7 +394,7 @@ func (b *cmdTaskBuilder) taskUpdateF(cmd *cobra.Command, args []string) error { return err } - var id influxdb.ID + var id platform.ID if err := id.DecodeFromString(b.taskID); err != nil { return err } @@ -437,7 +439,7 @@ func (b *cmdTaskBuilder) taskDeleteF(cmd *cobra.Command, args []string) error { return err } - var id influxdb.ID + var id platform.ID err = id.DecodeFromString(b.taskID) if err != nil { return err @@ -536,14 +538,14 @@ func (b *cmdTaskBuilder) taskLogFindF(cmd *cobra.Command, args []string) error { } var filter influxdb.LogFilter - id, err := influxdb.IDFromString(b.taskID) + id, err := platform.IDFromString(b.taskID) if err != nil { return err } filter.Task = *id if b.runID != "" { - id, err := influxdb.IDFromString(b.runID) + id, err := platform.IDFromString(b.runID) if err != nil { return err } @@ -624,7 +626,7 @@ func (b *cmdTaskBuilder) taskRunFindF(cmd *cobra.Command, args []string) error { AfterTime: b.taskRunFindFlags.afterTime, BeforeTime: b.taskRunFindFlags.beforeTime, } - taskID, err := influxdb.IDFromString(b.taskID) + taskID, err := platform.IDFromString(b.taskID) if err != nil { return err } @@ -632,7 +634,7 @@ func (b *cmdTaskBuilder) taskRunFindF(cmd *cobra.Command, args []string) error { var runs []*influxdb.Run if b.runID != "" { - id, err := influxdb.IDFromString(b.runID) + id, err := platform.IDFromString(b.runID) if err != nil { return err } @@ -714,7 +716,7 @@ func (b *cmdTaskBuilder) runRetryF(*cobra.Command, []string) error { return err } - var taskID, runID influxdb.ID + var taskID, runID platform.ID if err := taskID.DecodeFromString(runRetryFlags.taskID); err != nil { return err } diff --git a/cmd/influx/task_test.go b/cmd/influx/task_test.go index 9cfcbf7c5d5..37e030d3ebe 100644 --- a/cmd/influx/task_test.go +++ b/cmd/influx/task_test.go @@ -7,6 +7,8 @@ import ( "io/ioutil" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" @@ -17,7 +19,7 @@ import ( // Purpose of test suite: // checking if cmd line tool gives all data needed for TaskService to perform functions func TestCmdTask(t *testing.T) { - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) fakeSVCFn := func(svc influxdb.TaskService) taskSVCsFn { return func() (influxdb.TaskService, influxdb.OrganizationService, error) { diff --git a/cmd/influx/telegraf.go b/cmd/influx/telegraf.go index b6a158160dd..a66f80206d0 100644 --- a/cmd/influx/telegraf.go +++ b/cmd/influx/telegraf.go @@ -5,6 +5,9 @@ import ( "errors" "io/ioutil" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/cmd/influx/internal" "github.com/influxdata/influxdb/v2/http" @@ -76,14 +79,14 @@ func (b *cmdTelegrafBuilder) listRunE(cmd *cobra.Command, args []string) error { orgID, _ := b.org.getID(orgSVC) if orgID == 0 && b.id == "" { - return &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + return &errors2.Error{ + Code: errors2.EUnprocessableEntity, Msg: "at least one of org, org-id, or id must be provided", } } if b.id != "" { - id, err := influxdb.IDFromString(b.id) + id, err := platform.IDFromString(b.id) if err != nil { return err } @@ -190,13 +193,13 @@ func (b *cmdTelegrafBuilder) removeRunEFn(cmd *cobra.Command, args []string) err } for _, rawID := range b.ids { - id, err := influxdb.IDFromString(rawID) + id, err := platform.IDFromString(rawID) if err != nil { return err } err = svc.DeleteTelegrafConfig(context.Background(), *id) - if err != nil && influxdb.ErrorCode(err) != influxdb.ENotFound { + if err != nil && errors2.ErrorCode(err) != errors2.ENotFound { return err } } @@ -247,7 +250,7 @@ func (b *cmdTelegrafBuilder) updateRunEFn(cmd *cobra.Command, args []string) err return err } - id, err := influxdb.IDFromString(b.id) + id, err := platform.IDFromString(b.id) if err != nil { return err } @@ -309,8 +312,8 @@ func (b *cmdTelegrafBuilder) readConfig(file string) (string, error) { stdIn, err := inStdIn(b.in) if err != nil { - return "", &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + return "", &errors2.Error{ + Code: errors2.EUnprocessableEntity, Err: errors.New("a Telegraf config must be provided"), } } diff --git a/cmd/influx/template.go b/cmd/influx/template.go index 68aaa01a0db..d4ed07dce29 100644 --- a/cmd/influx/template.go +++ b/cmd/influx/template.go @@ -17,6 +17,8 @@ import ( "strings" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/fatih/color" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/cmd/influx/internal" @@ -216,7 +218,7 @@ func (b *cmdTemplateBuilder) applyRunEFn(cmd *cobra.Command, args []string) erro } } - var stackID influxdb.ID + var stackID platform.ID if b.stackID != "" { if err := stackID.DecodeFromString(b.stackID); err != nil { return err @@ -407,7 +409,7 @@ func (b *cmdTemplateBuilder) exportRunEFn(cmd *cobra.Command, args []string) err } if b.stackID != "" { - stackID, err := influxdb.IDFromString(b.stackID) + stackID, err := platform.IDFromString(b.stackID) if err != nil { return ierror.Wrap(err, "invalid stack ID provided") } @@ -558,7 +560,7 @@ func (b *cmdTemplateBuilder) exportStackRunEFn(cmd *cobra.Command, args []string return err } - stackID, err := influxdb.IDFromString(args[0]) + stackID, err := platform.IDFromString(args[0]) if err != nil { return err } @@ -718,9 +720,9 @@ func (b *cmdTemplateBuilder) stackListRunEFn(cmd *cobra.Command, args []string) return err } - var stackIDs []influxdb.ID + var stackIDs []platform.ID for _, rawID := range b.stackIDs { - id, err := influxdb.IDFromString(rawID) + id, err := platform.IDFromString(rawID) if err != nil { return err } @@ -774,9 +776,9 @@ func (b *cmdTemplateBuilder) stackRemoveRunEFn(cmd *cobra.Command, args []string return err } - var stackIDs []influxdb.ID + var stackIDs []platform.ID for _, rawID := range b.stackIDs { - id, err := influxdb.IDFromString(rawID) + id, err := platform.IDFromString(rawID) if err != nil { return err } @@ -820,7 +822,7 @@ func (b *cmdTemplateBuilder) stackRemoveRunEFn(cmd *cobra.Command, args []string } } - err := templateSVC.DeleteStack(context.Background(), struct{ OrgID, UserID, StackID influxdb.ID }{ + err := templateSVC.DeleteStack(context.Background(), struct{ OrgID, UserID, StackID platform.ID }{ OrgID: orgID, UserID: 0, StackID: stack.ID, @@ -883,7 +885,7 @@ func (b *cmdTemplateBuilder) stackUpdateRunEFn(cmd *cobra.Command, args []string return err } - stackID, err := influxdb.IDFromString(b.stackID) + stackID, err := platform.IDFromString(b.stackID) if err != nil { return ierror.Wrap(err, "required stack id is invalid") } @@ -917,7 +919,7 @@ func (b *cmdTemplateBuilder) stackUpdateRunEFn(cmd *cobra.Command, args []string return errors.New("resource type is invalid; got: " + b.exportOpts.resourceType) } - id, err := influxdb.IDFromString(idRaw) + id, err := platform.IDFromString(idRaw) if err != nil { return ierror.Wrap(err, fmt.Sprintf("%s resource id %q is invalid", kind, idRaw)) } @@ -1197,9 +1199,9 @@ func newResourcesToClone(kind pkger.Kind, idStrs, names []string) (pkger.ExportO return pkger.ExportWithExistingResources(resources...), nil } -func toInfluxIDs(args []string) ([]influxdb.ID, error) { +func toInfluxIDs(args []string) ([]platform.ID, error) { var ( - ids []influxdb.ID + ids []platform.ID errs []string ) for _, arg := range args { @@ -1208,7 +1210,7 @@ func toInfluxIDs(args []string) ([]influxdb.ID, error) { continue } - id, err := influxdb.IDFromString(normedArg) + id, err := platform.IDFromString(normedArg) if err != nil { errs = append(errs, "arg must provide a valid 16 length ID; got: "+arg) continue @@ -1568,7 +1570,7 @@ func (b *cmdTemplateBuilder) printTemplateDiff(diff pkger.Diff) error { return nil } -func (b *cmdTemplateBuilder) printTemplateSummary(stackID influxdb.ID, sum pkger.Summary) error { +func (b *cmdTemplateBuilder) printTemplateSummary(stackID platform.ID, sum pkger.Summary) error { if b.quiet { return nil } diff --git a/cmd/influx/template_test.go b/cmd/influx/template_test.go index 6a6688ace1e..0a664dd0a8d 100644 --- a/cmd/influx/template_test.go +++ b/cmd/influx/template_test.go @@ -15,6 +15,8 @@ import ( "strings" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" "github.com/influxdata/influxdb/v2/pkger" @@ -28,7 +30,7 @@ func Test_Template_Commands(t *testing.T) { return func() (pkger.SVC, influxdb.OrganizationService, error) { return svc, &mock.OrganizationService{ FindOrganizationF: func(ctx context.Context, filter influxdb.OrganizationFilter) (*influxdb.Organization, error) { - return &influxdb.Organization{ID: influxdb.ID(9000), Name: "influxdata"}, nil + return &influxdb.Organization{ID: platform.ID(9000), Name: "influxdata"}, nil }, }, nil } @@ -43,7 +45,7 @@ func Test_Template_Commands(t *testing.T) { assert.Equal(t, "bucket1", sum.Buckets[0].Name) } - expectedOrgID := influxdb.ID(9000) + expectedOrgID := platform.ID(9000) tests := []struct { templateFileArgs @@ -246,15 +248,15 @@ func Test_Template_Commands(t *testing.T) { tests := []struct { name string templateFileArgs - bucketIDs []influxdb.ID - dashIDs []influxdb.ID - endpointIDs []influxdb.ID - labelIDs []influxdb.ID - ruleIDs []influxdb.ID - taskIDs []influxdb.ID - telegrafIDs []influxdb.ID - varIDs []influxdb.ID - stackID influxdb.ID + bucketIDs []platform.ID + dashIDs []platform.ID + endpointIDs []platform.ID + labelIDs []platform.ID + ruleIDs []platform.ID + taskIDs []platform.ID + telegrafIDs []platform.ID + varIDs []platform.ID + stackID platform.ID }{ { templateFileArgs: templateFileArgs{ @@ -262,7 +264,7 @@ func Test_Template_Commands(t *testing.T) { encoding: pkger.EncodingYAML, filename: "pkg_0.yml", }, - bucketIDs: []influxdb.ID{1, 2}, + bucketIDs: []platform.ID{1, 2}, }, { templateFileArgs: templateFileArgs{ @@ -270,7 +272,7 @@ func Test_Template_Commands(t *testing.T) { encoding: pkger.EncodingYAML, filename: "pkg_0.yml", }, - dashIDs: []influxdb.ID{1, 2}, + dashIDs: []platform.ID{1, 2}, }, { templateFileArgs: templateFileArgs{ @@ -278,7 +280,7 @@ func Test_Template_Commands(t *testing.T) { encoding: pkger.EncodingYAML, filename: "pkg_0.yml", }, - endpointIDs: []influxdb.ID{1, 2}, + endpointIDs: []platform.ID{1, 2}, }, { templateFileArgs: templateFileArgs{ @@ -286,7 +288,7 @@ func Test_Template_Commands(t *testing.T) { encoding: pkger.EncodingYAML, filename: "pkg_0.yml", }, - labelIDs: []influxdb.ID{1, 2}, + labelIDs: []platform.ID{1, 2}, }, { templateFileArgs: templateFileArgs{ @@ -294,7 +296,7 @@ func Test_Template_Commands(t *testing.T) { encoding: pkger.EncodingYAML, filename: "pkg_0.yml", }, - ruleIDs: []influxdb.ID{1, 2}, + ruleIDs: []platform.ID{1, 2}, }, { templateFileArgs: templateFileArgs{ @@ -302,7 +304,7 @@ func Test_Template_Commands(t *testing.T) { encoding: pkger.EncodingYAML, filename: "pkg_0.yml", }, - taskIDs: []influxdb.ID{1, 2}, + taskIDs: []platform.ID{1, 2}, }, { templateFileArgs: templateFileArgs{ @@ -310,7 +312,7 @@ func Test_Template_Commands(t *testing.T) { encoding: pkger.EncodingYAML, filename: "pkg_0.yml", }, - telegrafIDs: []influxdb.ID{1, 2}, + telegrafIDs: []platform.ID{1, 2}, }, { templateFileArgs: templateFileArgs{ @@ -318,7 +320,7 @@ func Test_Template_Commands(t *testing.T) { encoding: pkger.EncodingYAML, filename: "pkg_0.yml", }, - varIDs: []influxdb.ID{1, 2}, + varIDs: []platform.ID{1, 2}, }, } @@ -368,7 +370,7 @@ func Test_Template_Commands(t *testing.T) { testPkgWrites(t, cmdFn, tt.templateFileArgs, func(t *testing.T, pkg *pkger.Template) { sum := pkg.Summary() - kindToName := func(k pkger.Kind, id influxdb.ID) string { + kindToName := func(k pkger.Kind, id platform.ID) string { return strings.ToLower(k.String()) + strconv.Itoa(int(id)) } @@ -448,7 +450,7 @@ func Test_Template_Commands(t *testing.T) { name: "stack", encoding: pkger.EncodingYAML, filename: "pkg_0.yml", - args: []string{"export", "--stack-id=" + influxdb.ID(1).String()}, + args: []string{"export", "--stack-id=" + platform.ID(1).String()}, } testPkgWrites(t, cmdFn, tmplFileArgs, func(t *testing.T, pkg *pkger.Template) { @@ -509,7 +511,7 @@ func Test_Template_Commands(t *testing.T) { }{ { name: "when only org and token provided is successful", - args: []string{"--org-id=" + influxdb.ID(1).String()}, + args: []string{"--org-id=" + platform.ID(1).String()}, expectedStack: pkger.Stack{ OrgID: 1, Events: []pkger.StackEvent{{ @@ -520,7 +522,7 @@ func Test_Template_Commands(t *testing.T) { { name: "when org and name provided provided is successful", args: []string{ - "--org-id=" + influxdb.ID(1).String(), + "--org-id=" + platform.ID(1).String(), "--stack-name=foo", }, expectedStack: pkger.Stack{ @@ -534,7 +536,7 @@ func Test_Template_Commands(t *testing.T) { { name: "when all flags provided provided is successful", args: []string{ - "--org-id=" + influxdb.ID(1).String(), + "--org-id=" + platform.ID(1).String(), "--stack-name=foo", "--stack-description=desc", "--template-url=http://example.com/1", @@ -556,7 +558,7 @@ func Test_Template_Commands(t *testing.T) { { name: "when all shorthand flags provided provided is successful", args: []string{ - "--org-id=" + influxdb.ID(1).String(), + "--org-id=" + platform.ID(1).String(), "-n=foo", "-d=desc", "-u=http://example.com/1", @@ -595,7 +597,7 @@ func Test_Template_Commands(t *testing.T) { rootCmd := builder.cmd(func(f *globalFlags, opt genericCLIOpts) *cobra.Command { echoSVC := &fakePkgSVC{ - initStackFn: func(ctx context.Context, userID influxdb.ID, stCreate pkger.StackCreate) (pkger.Stack, error) { + initStackFn: func(ctx context.Context, userID platform.ID, stCreate pkger.StackCreate) (pkger.Stack, error) { return pkger.Stack{ ID: 9000, OrgID: stCreate.OrgID, @@ -731,7 +733,7 @@ func Test_Template_Commands(t *testing.T) { return newCmdPkgerBuilder(fakeSVCFn(echoSVC), f, opt).cmdStacks() }) - baseArgs := []string{"stacks", "update", "--stack-id=" + influxdb.ID(1).String(), "--json"} + baseArgs := []string{"stacks", "update", "--stack-id=" + platform.ID(1).String(), "--json"} rootCmd.SetArgs(append(baseArgs, tt.args...)) @@ -888,39 +890,39 @@ func testPkgWritesToBuffer(newCmdFn func(w io.Writer) *cobra.Command, args templ } type fakePkgSVC struct { - initStackFn func(ctx context.Context, userID influxdb.ID, stack pkger.StackCreate) (pkger.Stack, error) + initStackFn func(ctx context.Context, userID platform.ID, stack pkger.StackCreate) (pkger.Stack, error) updateStackFn func(ctx context.Context, upd pkger.StackUpdate) (pkger.Stack, error) exportFn func(ctx context.Context, setters ...pkger.ExportOptFn) (*pkger.Template, error) - dryRunFn func(ctx context.Context, orgID, userID influxdb.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) - applyFn func(ctx context.Context, orgID, userID influxdb.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) + dryRunFn func(ctx context.Context, orgID, userID platform.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) + applyFn func(ctx context.Context, orgID, userID platform.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) } var _ pkger.SVC = (*fakePkgSVC)(nil) -func (f *fakePkgSVC) InitStack(ctx context.Context, userID influxdb.ID, stack pkger.StackCreate) (pkger.Stack, error) { +func (f *fakePkgSVC) InitStack(ctx context.Context, userID platform.ID, stack pkger.StackCreate) (pkger.Stack, error) { if f.initStackFn != nil { return f.initStackFn(ctx, userID, stack) } panic("not implemented") } -func (f *fakePkgSVC) ListStacks(ctx context.Context, orgID influxdb.ID, filter pkger.ListFilter) ([]pkger.Stack, error) { +func (f *fakePkgSVC) ListStacks(ctx context.Context, orgID platform.ID, filter pkger.ListFilter) ([]pkger.Stack, error) { panic("not implemented") } -func (f *fakePkgSVC) UninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) (pkger.Stack, error) { +func (f *fakePkgSVC) UninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) (pkger.Stack, error) { panic("not implemeted") } -func (f *fakePkgSVC) DeleteStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) error { +func (f *fakePkgSVC) DeleteStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) error { panic("not implemented") } -func (f *fakePkgSVC) ExportStack(ctx context.Context, orgID, stackID influxdb.ID) (*pkger.Template, error) { +func (f *fakePkgSVC) ExportStack(ctx context.Context, orgID, stackID platform.ID) (*pkger.Template, error) { panic("not implemented") } -func (f *fakePkgSVC) ReadStack(ctx context.Context, id influxdb.ID) (pkger.Stack, error) { +func (f *fakePkgSVC) ReadStack(ctx context.Context, id platform.ID) (pkger.Stack, error) { panic("not implemented") } @@ -938,14 +940,14 @@ func (f *fakePkgSVC) Export(ctx context.Context, setters ...pkger.ExportOptFn) ( panic("not implemented") } -func (f *fakePkgSVC) DryRun(ctx context.Context, orgID, userID influxdb.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { +func (f *fakePkgSVC) DryRun(ctx context.Context, orgID, userID platform.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { if f.dryRunFn != nil { return f.dryRunFn(ctx, orgID, userID, opts...) } panic("not implemented") } -func (f *fakePkgSVC) Apply(ctx context.Context, orgID, userID influxdb.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { +func (f *fakePkgSVC) Apply(ctx context.Context, orgID, userID platform.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { if f.applyFn != nil { return f.applyFn(ctx, orgID, userID, opts...) } @@ -968,7 +970,7 @@ func newTempFile(t *testing.T, dir string) *os.File { return f } -func idsStr(ids ...influxdb.ID) string { +func idsStr(ids ...platform.ID) string { var idStrs []string for _, id := range ids { idStrs = append(idStrs, id.String()) diff --git a/cmd/influx/user.go b/cmd/influx/user.go index 533070c5414..eed72db19eb 100644 --- a/cmd/influx/user.go +++ b/cmd/influx/user.go @@ -4,6 +4,8 @@ import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/cmd/internal" "github.com/influxdata/influxdb/v2/http" @@ -87,7 +89,7 @@ func (b *cmdUserBuilder) cmdPasswordRunEFn(cmd *cobra.Command, args []string) er filter.Name = &b.name } if b.id != "" { - id, err := influxdb.IDFromString(b.id) + id, err := platform.IDFromString(b.id) if err != nil { return err } @@ -128,7 +130,7 @@ func (b *cmdUserBuilder) cmdUpdateRunEFn(cmd *cobra.Command, args []string) erro return err } - var id influxdb.ID + var id platform.ID if err := id.DecodeFromString(b.id); err != nil { return err } @@ -257,7 +259,7 @@ func (b *cmdUserBuilder) cmdFindRunEFn(*cobra.Command, []string) error { filter.Name = &b.name } if b.id != "" { - id, err := influxdb.IDFromString(b.id) + id, err := platform.IDFromString(b.id) if err != nil { return err } @@ -289,7 +291,7 @@ func (b *cmdUserBuilder) cmdDeleteRunEFn(cmd *cobra.Command, args []string) erro return err } - var id influxdb.ID + var id platform.ID if err := id.DecodeFromString(b.id); err != nil { return err } diff --git a/cmd/influx/user_test.go b/cmd/influx/user_test.go index 37a2aa439a3..0ad29de4d2c 100644 --- a/cmd/influx/user_test.go +++ b/cmd/influx/user_test.go @@ -9,6 +9,8 @@ import ( "reflect" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/cmd/internal" "github.com/influxdata/influxdb/v2/mock" @@ -19,7 +21,7 @@ import ( ) func TestCmdUser(t *testing.T) { - var org = &influxdb.Organization{ID: influxdb.ID(9000), Name: "org name"} + var org = &influxdb.Organization{ID: platform.ID(9000), Name: "org name"} var orgNameFlag = fmt.Sprintf("--org=%s", org.Name) type orgSetResult struct { @@ -156,7 +158,7 @@ func TestCmdUser(t *testing.T) { return nil } passSVC := mock.NewPasswordsService() - passSVC.SetPasswordFn = func(ctx context.Context, id influxdb.ID, password string) error { + passSVC.SetPasswordFn = func(ctx context.Context, id platform.ID, password string) error { if expected.password != password { return fmt.Errorf("unexpected password;\n\twant= %+v\n\tgot= %+v", expected.password, password) } @@ -220,27 +222,27 @@ func TestCmdUser(t *testing.T) { t.Run("delete", func(t *testing.T) { tests := []struct { name string - expectedID influxdb.ID + expectedID platform.ID flag string }{ { name: "long id", - expectedID: influxdb.ID(1), + expectedID: platform.ID(1), flag: "--id=", }, { name: "shorts", - expectedID: influxdb.ID(1), + expectedID: platform.ID(1), flag: "-i=", }, } - cmdFn := func(expectedID influxdb.ID) func(*globalFlags, genericCLIOpts) *cobra.Command { + cmdFn := func(expectedID platform.ID) func(*globalFlags, genericCLIOpts) *cobra.Command { svc := mock.NewUserService() - svc.FindUserByIDFn = func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + svc.FindUserByIDFn = func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ID: id}, nil } - svc.DeleteUserFn = func(ctx context.Context, id influxdb.ID) error { + svc.DeleteUserFn = func(ctx context.Context, id platform.ID) error { if expectedID != id { return fmt.Errorf("unexpected id:\n\twant= %s\n\tgot= %s", expectedID, id) } @@ -273,7 +275,7 @@ func TestCmdUser(t *testing.T) { t.Run("list", func(t *testing.T) { type called struct { name string - id influxdb.ID + id platform.ID } tests := []struct { @@ -285,7 +287,7 @@ func TestCmdUser(t *testing.T) { { name: "id", flags: []string{ - "--id=" + influxdb.ID(2).String(), + "--id=" + platform.ID(2).String(), }, expected: called{ id: 2, @@ -300,7 +302,7 @@ func TestCmdUser(t *testing.T) { name: "shorts", flags: []string{ "-n=name1", - "-i=" + influxdb.ID(1).String(), + "-i=" + platform.ID(1).String(), }, expected: called{name: "name1", id: 1}, }, @@ -308,7 +310,7 @@ func TestCmdUser(t *testing.T) { name: "ls alias", command: "ls", flags: []string{ - "--id=" + influxdb.ID(2).String(), + "--id=" + platform.ID(2).String(), }, expected: called{ id: 2, @@ -318,7 +320,7 @@ func TestCmdUser(t *testing.T) { name: "find alias", command: "find", flags: []string{ - "--id=" + influxdb.ID(2).String(), + "--id=" + platform.ID(2).String(), }, expected: called{ id: 2, @@ -378,7 +380,7 @@ func TestCmdUser(t *testing.T) { { name: "basic just name", flags: []string{ - "--id=" + influxdb.ID(3).String(), + "--id=" + platform.ID(3).String(), "--name=new name", }, expected: influxdb.UserUpdate{ @@ -388,7 +390,7 @@ func TestCmdUser(t *testing.T) { { name: "with all fields", flags: []string{ - "--id=" + influxdb.ID(3).String(), + "--id=" + platform.ID(3).String(), "--name=new name", }, expected: influxdb.UserUpdate{ @@ -398,7 +400,7 @@ func TestCmdUser(t *testing.T) { { name: "shorts", flags: []string{ - "-i=" + influxdb.ID(3).String(), + "-i=" + platform.ID(3).String(), "-n=new name", }, expected: influxdb.UserUpdate{ @@ -409,9 +411,9 @@ func TestCmdUser(t *testing.T) { cmdFn := func(expectedUpdate influxdb.UserUpdate) func(*globalFlags, genericCLIOpts) *cobra.Command { svc := mock.NewUserService() - svc.UpdateUserFn = func(ctx context.Context, id influxdb.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { + svc.UpdateUserFn = func(ctx context.Context, id platform.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { if id != 3 { - return nil, fmt.Errorf("unexpecte id:\n\twant= %s\n\tgot= %s", influxdb.ID(3), id) + return nil, fmt.Errorf("unexpecte id:\n\twant= %s\n\tgot= %s", platform.ID(3), id) } if !reflect.DeepEqual(expectedUpdate, upd) { return nil, fmt.Errorf("unexpected User update;\n\twant= %+v\n\tgot= %+v", expectedUpdate, upd) @@ -450,14 +452,14 @@ func TestCmdUser(t *testing.T) { { name: "basic id", flags: []string{ - "--id=" + influxdb.ID(3).String(), + "--id=" + platform.ID(3).String(), }, expected: "pass1", }, { name: "shorts", flags: []string{ - "-i=" + influxdb.ID(3).String(), + "-i=" + platform.ID(3).String(), "-n=new name", }, expected: "pass1", @@ -477,7 +479,7 @@ func TestCmdUser(t *testing.T) { return usr, nil } passSVC := mock.NewPasswordsService() - passSVC.SetPasswordFn = func(ctx context.Context, id influxdb.ID, pass string) error { + passSVC.SetPasswordFn = func(ctx context.Context, id platform.ID, pass string) error { if pass != expected { return fmt.Errorf("unexpecte id:\n\twant= %s\n\tgot= %s", pass, expected) } diff --git a/cmd/influx/v1_authorization.go b/cmd/influx/v1_authorization.go index 6b956be75c7..1b22b13cde0 100644 --- a/cmd/influx/v1_authorization.go +++ b/cmd/influx/v1_authorization.go @@ -6,6 +6,8 @@ import ( "fmt" "io" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/cmd/influx/internal" cinternal "github.com/influxdata/influxdb/v2/cmd/internal" @@ -16,12 +18,12 @@ import ( ) type v1Token struct { - ID influxdb.ID `json:"id"` + ID platform.ID `json:"id"` Description string `json:"description"` Token string `json:"token"` Status string `json:"status"` UserName string `json:"userName"` - UserID influxdb.ID `json:"userID"` + UserID platform.ID `json:"userID"` Permissions []string `json:"permissions"` } @@ -142,7 +144,7 @@ func makeV1AuthorizationCreateE(opt genericCLIOpts) func(*cobra.Command, []strin var permissions []influxdb.Permission for _, bp := range bucketPerms { for _, p := range bp.perms { - var id influxdb.ID + var id platform.ID if err := id.DecodeFromString(p); err != nil { return fmt.Errorf("invalid bucket ID '%s': %w (did you pass a bucket name instead of an ID?)", p, err) } @@ -251,7 +253,7 @@ func v1AuthorizationFindF(cmd *cobra.Command, _ []string) error { filter.User = &v1AuthorizationFindFlags.user } if v1AuthorizationFindFlags.userID != "" { - uID, err := influxdb.IDFromString(v1AuthorizationFindFlags.userID) + uID, err := platform.IDFromString(v1AuthorizationFindFlags.userID) if err != nil { return fmt.Errorf("invalid user ID '%s': %w (did you pass a username instead of an ID?)", v1AuthorizationFindFlags.userID, err) } @@ -261,7 +263,7 @@ func v1AuthorizationFindF(cmd *cobra.Command, _ []string) error { filter.Org = &v1AuthorizationFindFlags.org.name } if v1AuthorizationFindFlags.org.id != "" { - oID, err := influxdb.IDFromString(v1AuthorizationFindFlags.org.id) + oID, err := platform.IDFromString(v1AuthorizationFindFlags.org.id) if err != nil { return fmt.Errorf("invalid org ID '%s': %w (did you pass an org name instead of an ID?)", v1AuthorizationFindFlags.org.id, err) } @@ -548,7 +550,7 @@ func v1FindOneAuthorization(s *authorization.Client, filter influxdb.Authorizati } type v1AuthLookupFlags struct { - id influxdb.ID + id platform.ID username string required bool // required when set to true determines whether validate expects either id or username to be set } diff --git a/cmd/influx/v1_dbrp.go b/cmd/influx/v1_dbrp.go index 3f62d76d655..56b165fff15 100644 --- a/cmd/influx/v1_dbrp.go +++ b/cmd/influx/v1_dbrp.go @@ -4,6 +4,8 @@ import ( "context" "io" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/cmd/influx/internal" "github.com/influxdata/influxdb/v2/dbrp" @@ -33,10 +35,10 @@ var v1DBRPCRUDFlags struct { } var v1DBRPFindFlags struct { - BucketID influxdb.ID // Specifies the bucket ID to filter on + BucketID platform.ID // Specifies the bucket ID to filter on DB string // Specifies the database to filter on Default *bool // Specifies filtering on default - ID influxdb.ID // Specifies the mapping ID to filter on + ID platform.ID // Specifies the mapping ID to filter on Org organization // required // Specifies the organization ID to filter on RP string // Specifies the retention policy to filter on } @@ -121,7 +123,7 @@ func v1DBRPFindF(cmd *cobra.Command, _ []string) error { } var v1DBRPCreateFlags struct { - BucketID influxdb.ID // Specifies the bucket ID to associate with the mapping + BucketID platform.ID // Specifies the bucket ID to associate with the mapping DB string // Specifies the database of the database Default bool // Specifies filtering on default Org organization // Specifies the organization ID to filter on @@ -237,7 +239,7 @@ func v1WriteDBRPs(w io.Writer, printOpts v1DBRPPrintOpt) error { } var v1DBRPDeleteFlags struct { - ID influxdb.ID + ID platform.ID Org organization } @@ -292,7 +294,7 @@ func v1DBRPDeleteF(cmd *cobra.Command, _ []string) error { } var v1DBRPUpdateFlags struct { - ID influxdb.ID // Specifies the mapping ID to update + ID platform.ID // Specifies the mapping ID to update Org organization // Specifies the organization ID Default *bool // A nil value means that Default is unset in the Flags RP string // Updated name of the retention policy diff --git a/cmd/influx/write.go b/cmd/influx/write.go index ceb1b7ce612..2dc14f34d20 100644 --- a/cmd/influx/write.go +++ b/cmd/influx/write.go @@ -14,6 +14,8 @@ import ( "strconv" "strings" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/fujiwara/shapeio" platform "github.com/influxdata/influxdb/v2" ihttp "github.com/influxdata/influxdb/v2/http" @@ -366,7 +368,7 @@ func (b *writeFlagsBuilder) writeRunE(cmd *cobra.Command, args []string) error { ) if b.BucketID != "" { - filter.ID, err = platform.IDFromString(b.BucketID) + filter.ID, err = platform2.IDFromString(b.BucketID) if err != nil { return fmt.Errorf("failed to decode bucket-id: %v", err) } @@ -376,7 +378,7 @@ func (b *writeFlagsBuilder) writeRunE(cmd *cobra.Command, args []string) error { } if b.org.id != "" { - filter.OrganizationID, err = platform.IDFromString(b.org.id) + filter.OrganizationID, err = platform2.IDFromString(b.org.id) if err != nil { return fmt.Errorf("failed to decode org-id id: %v", err) } diff --git a/cmd/influxd/inspect/export_lp.go b/cmd/influxd/inspect/export_lp.go index 8f329be9fd3..35890f326e0 100644 --- a/cmd/influxd/inspect/export_lp.go +++ b/cmd/influxd/inspect/export_lp.go @@ -13,7 +13,8 @@ import ( "sync" "time" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/cli" "github.com/influxdata/influxdb/v2/models" "github.com/influxdata/influxdb/v2/pkg/escape" @@ -27,7 +28,7 @@ import ( // exportFlags contains CLI-compatible forms of export options. type exportFlags struct { enginePath string - bucketID influxdb.ID + bucketID platform.ID measurements []string startTime string endTime string @@ -206,7 +207,7 @@ func exportRunE(cmd *cobra.Command, flags *exportFlags) error { } // exportTSMs finds, reads, and exports all data stored in TSM files for a bucket that matches a set of filters. -func exportTSMs(engineDir string, bucketID influxdb.ID, filters *exportFilters, out io.Writer, log *zap.Logger) error { +func exportTSMs(engineDir string, bucketID platform.ID, filters *exportFilters, out io.Writer, log *zap.Logger) error { // TSM is stored under `/data////*.tsm` tsmDir := filepath.Join(engineDir, "data", bucketID.String()) tsmPattern := filepath.Join(tsmDir, "*", "*", fmt.Sprintf("*.%s", tsm1.TSMFileExtension)) @@ -289,7 +290,7 @@ func exportTSM(tsmFile string, filters *exportFilters, out io.Writer, log *zap.L // // N.B. exported lines can include some duplicates from a matching call to exportTSMs on the same engine/bucket. // This is OK since writes are idempotent. -func exportWALs(engineDir string, bucketID influxdb.ID, filters *exportFilters, out io.Writer, log *zap.Logger) error { +func exportWALs(engineDir string, bucketID platform.ID, filters *exportFilters, out io.Writer, log *zap.Logger) error { // WAL is stored under `/wal////*.wal` walDir := filepath.Join(engineDir, "wal", bucketID.String()) walPattern := filepath.Join(walDir, "*", "*", fmt.Sprintf("*.%s", tsm1.WALFileExtension)) diff --git a/cmd/influxd/launcher/backup_restore_test.go b/cmd/influxd/launcher/backup_restore_test.go index 29820c18b13..70aee46a410 100644 --- a/cmd/influxd/launcher/backup_restore_test.go +++ b/cmd/influxd/launcher/backup_restore_test.go @@ -2,6 +2,7 @@ package launcher_test import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "io/ioutil" "os" "testing" @@ -80,7 +81,7 @@ func TestBackupRestore_Full(t *testing.T) { // Check that orgs and buckets were reset to match the original server's metadata. _, err = l2.OrgService(t).FindOrganizationByID(ctx, l2.Org.ID) - require.Equal(t, influxdb.ENotFound, influxdb.ErrorCode(err)) + require.Equal(t, errors.ENotFound, errors.ErrorCode(err)) rbkt1, err := l2.BucketService(t).FindBucket(ctx, influxdb.BucketFilter{OrganizationID: &l1.Org.ID, ID: &l1.Bucket.ID}) require.NoError(t, err) require.Equal(t, l1.Bucket.Name, rbkt1.Name) @@ -88,7 +89,7 @@ func TestBackupRestore_Full(t *testing.T) { require.NoError(t, err) require.Equal(t, b1.Name, rbkt2.Name) _, err = l2.BucketService(t).FindBucket(ctx, influxdb.BucketFilter{OrganizationID: &l2.Org.ID, ID: &b2.ID}) - require.Equal(t, influxdb.ENotFound, influxdb.ErrorCode(err)) + require.Equal(t, errors.ENotFound, errors.ErrorCode(err)) // Check that data was restored to buckets. q1 := `from(bucket:"BUCKET") |> range(start:2000-01-01T00:00:00Z,stop:2000-01-02T00:00:00Z)` diff --git a/cmd/influxd/launcher/engine.go b/cmd/influxd/launcher/engine.go index 0b1c9a7fc23..f9f9abd4475 100644 --- a/cmd/influxd/launcher/engine.go +++ b/cmd/influxd/launcher/engine.go @@ -8,6 +8,8 @@ import ( "sync" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/http" "github.com/influxdata/influxdb/v2/kit/prom" @@ -29,7 +31,7 @@ type Engine interface { influxdb.BackupService influxdb.RestoreService - SeriesCardinality(orgID, bucketID influxdb.ID) int64 + SeriesCardinality(orgID, bucketID platform.ID) int64 TSDBStore() storage.TSDBStore MetaClient() storage.MetaClient @@ -109,17 +111,17 @@ func (t *TemporaryEngine) Close() error { } // WritePoints stores points into the storage engine. -func (t *TemporaryEngine) WritePoints(ctx context.Context, orgID influxdb.ID, bucketID influxdb.ID, points []models.Point) error { +func (t *TemporaryEngine) WritePoints(ctx context.Context, orgID platform.ID, bucketID platform.ID, points []models.Point) error { return t.engine.WritePoints(ctx, orgID, bucketID, points) } // SeriesCardinality returns the number of series in the engine. -func (t *TemporaryEngine) SeriesCardinality(orgID, bucketID influxdb.ID) int64 { +func (t *TemporaryEngine) SeriesCardinality(orgID, bucketID platform.ID) int64 { return t.engine.SeriesCardinality(orgID, bucketID) } // DeleteBucketRangePredicate will delete a bucket from the range and predicate. -func (t *TemporaryEngine) DeleteBucketRangePredicate(ctx context.Context, orgID, bucketID influxdb.ID, min, max int64, pred influxdb.Predicate) error { +func (t *TemporaryEngine) DeleteBucketRangePredicate(ctx context.Context, orgID, bucketID platform.ID, min, max int64, pred influxdb.Predicate) error { return t.engine.DeleteBucketRangePredicate(ctx, orgID, bucketID, min, max, pred) } @@ -127,12 +129,12 @@ func (t *TemporaryEngine) CreateBucket(ctx context.Context, b *influxdb.Bucket) return t.engine.CreateBucket(ctx, b) } -func (t *TemporaryEngine) UpdateBucketRetentionPolicy(ctx context.Context, bucketID influxdb.ID, upd *influxdb.BucketUpdate) error { +func (t *TemporaryEngine) UpdateBucketRetentionPolicy(ctx context.Context, bucketID platform.ID, upd *influxdb.BucketUpdate) error { return t.engine.UpdateBucketRetentionPolicy(ctx, bucketID, upd) } // DeleteBucket deletes a bucket from the time-series data. -func (t *TemporaryEngine) DeleteBucket(ctx context.Context, orgID, bucketID influxdb.ID) error { +func (t *TemporaryEngine) DeleteBucket(ctx context.Context, orgID, bucketID platform.ID) error { return t.engine.DeleteBucket(ctx, orgID, bucketID) } @@ -166,7 +168,7 @@ func (t *TemporaryEngine) RestoreKVStore(ctx context.Context, r io.Reader) error return t.engine.RestoreKVStore(ctx, r) } -func (t *TemporaryEngine) RestoreBucket(ctx context.Context, id influxdb.ID, dbi []byte) (map[uint64]uint64, error) { +func (t *TemporaryEngine) RestoreBucket(ctx context.Context, id platform.ID, dbi []byte) (map[uint64]uint64, error) { return t.engine.RestoreBucket(ctx, id, dbi) } diff --git a/cmd/influxd/launcher/launcher.go b/cmd/influxd/launcher/launcher.go index 8cea965494c..2e8828c5165 100644 --- a/cmd/influxd/launcher/launcher.go +++ b/cmd/influxd/launcher/launcher.go @@ -14,6 +14,8 @@ import ( "sync" "time" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/flux" "github.com/influxdata/flux/dependencies/testing" platform "github.com/influxdata/influxdb/v2" @@ -480,7 +482,7 @@ func (m *Launcher) run(ctx context.Context, opts *InfluxdOpts) (err error) { scheduler.WithOnErrorFn(func(ctx context.Context, taskID scheduler.ID, scheduledAt time.Time, err error) { schLogger.Info( "error in scheduler run", - zap.String("taskID", platform.ID(taskID).String()), + zap.String("taskID", platform2.ID(taskID).String()), zap.Time("scheduledAt", scheduledAt), zap.Error(err)) }), @@ -506,7 +508,7 @@ func (m *Launcher) run(ctx context.Context, opts *InfluxdOpts) (err error) { taskSvc, combinedTaskService, taskCoord, - func(ctx context.Context, taskID platform.ID, runID platform.ID) error { + func(ctx context.Context, taskID platform2.ID, runID platform2.ID) error { _, err := executor.ResumeCurrentRun(ctx, taskID, runID) return err }, diff --git a/cmd/influxd/launcher/pkger_test.go b/cmd/influxd/launcher/pkger_test.go index 5e73a32b669..ed3b201e8d8 100644 --- a/cmd/influxd/launcher/pkger_test.go +++ b/cmd/influxd/launcher/pkger_test.go @@ -12,6 +12,9 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" "github.com/influxdata/influxdb/v2/notification" @@ -38,9 +41,9 @@ func TestLauncher_Pkger(t *testing.T) { resourceCheck := newResourceChecker(l) - deleteStackFn := func(t *testing.T, stackID influxdb.ID) { + deleteStackFn := func(t *testing.T, stackID platform.ID) { t.Helper() - err := svc.DeleteStack(ctx, struct{ OrgID, UserID, StackID influxdb.ID }{ + err := svc.DeleteStack(ctx, struct{ OrgID, UserID, StackID platform.ID }{ OrgID: l.Org.ID, UserID: l.User.ID, StackID: stackID, @@ -256,7 +259,7 @@ func TestLauncher_Pkger(t *testing.T) { for _, b := range summary.Buckets { _, err := resourceCheck.getBucket(t, bySafeID(b.ID)) - assertErrorCode(t, influxdb.ENotFound, err) + assertErrorCode(t, errors2.ENotFound, err) } for _, c := range summary.Checks { @@ -266,12 +269,12 @@ func TestLauncher_Pkger(t *testing.T) { for _, d := range summary.Dashboards { _, err := resourceCheck.getDashboard(t, bySafeID(d.ID)) - assertErrorCode(t, influxdb.ENotFound, err) + assertErrorCode(t, errors2.ENotFound, err) } for _, l := range summary.Labels { _, err := resourceCheck.getLabel(t, bySafeID(l.ID)) - assertErrorCode(t, influxdb.ENotFound, err) + assertErrorCode(t, errors2.ENotFound, err) } for _, e := range summary.NotificationEndpoints { @@ -296,7 +299,7 @@ func TestLauncher_Pkger(t *testing.T) { for _, v := range summary.Variables { _, err := resourceCheck.getVariable(t, bySafeID(v.ID)) - assertErrorCode(t, influxdb.ENotFound, err) + assertErrorCode(t, errors2.ENotFound, err) } } @@ -336,7 +339,7 @@ func TestLauncher_Pkger(t *testing.T) { t.Run("filters stacks by ID filter", func(t *testing.T) { stacks, err := svc.ListStacks(ctx, l.Org.ID, pkger.ListFilter{ - StackIDs: []influxdb.ID{newStack1.ID}, + StackIDs: []platform.ID{newStack1.ID}, }) require.NoError(t, err) require.Len(t, stacks, 1) @@ -408,7 +411,7 @@ func TestLauncher_Pkger(t *testing.T) { require.Len(t, sum.Variables, 1) assert.NotZero(t, sum.Variables[0].ID) - _, err = svc.UninstallStack(ctx, struct{ OrgID, UserID, StackID influxdb.ID }{ + _, err = svc.UninstallStack(ctx, struct{ OrgID, UserID, StackID platform.ID }{ OrgID: l.Org.ID, UserID: l.User.ID, StackID: newStack.ID, @@ -471,7 +474,7 @@ func TestLauncher_Pkger(t *testing.T) { require.Len(t, sum.Variables, 1) assert.NotZero(t, sum.Variables[0].ID) - err = svc.DeleteStack(ctx, struct{ OrgID, UserID, StackID influxdb.ID }{ + err = svc.DeleteStack(ctx, struct{ OrgID, UserID, StackID platform.ID }{ OrgID: l.Org.ID, UserID: l.User.ID, StackID: newStack.ID, @@ -485,7 +488,7 @@ func TestLauncher_Pkger(t *testing.T) { newStack, cleanup := newStackFn(t, pkger.StackCreate{}) defer cleanup() - err := svc.DeleteStack(ctx, struct{ OrgID, UserID, StackID influxdb.ID }{ + err := svc.DeleteStack(ctx, struct{ OrgID, UserID, StackID platform.ID }{ OrgID: l.Org.ID, UserID: l.User.ID, StackID: newStack.ID, @@ -493,7 +496,7 @@ func TestLauncher_Pkger(t *testing.T) { require.NoError(t, err) // delete same stack - err = svc.DeleteStack(ctx, struct{ OrgID, UserID, StackID influxdb.ID }{ + err = svc.DeleteStack(ctx, struct{ OrgID, UserID, StackID platform.ID }{ OrgID: l.Org.ID, UserID: l.User.ID, StackID: newStack.ID, @@ -503,7 +506,7 @@ func TestLauncher_Pkger(t *testing.T) { t.Run("that doesn't exist should be successful", func(t *testing.T) { // delete stack that doesn't exist - err := svc.DeleteStack(ctx, struct{ OrgID, UserID, StackID influxdb.ID }{ + err := svc.DeleteStack(ctx, struct{ OrgID, UserID, StackID platform.ID }{ OrgID: l.Org.ID, UserID: l.User.ID, StackID: 9000, @@ -531,8 +534,8 @@ func TestLauncher_Pkger(t *testing.T) { require.NoError(t, err) assert.Equal(t, newStack2, actual) - _, err = svc.ReadStack(ctx, influxdb.ID(9000)) - require.Equal(t, influxdb.ENotFound, influxdb.ErrorCode(err)) + _, err = svc.ReadStack(ctx, platform.ID(9000)) + require.Equal(t, errors2.ENotFound, errors2.ErrorCode(err)) }) t.Run("updating a stack", func(t *testing.T) { @@ -687,7 +690,7 @@ func TestLauncher_Pkger(t *testing.T) { sumEquals(t, impact) stacks, err := svc.ListStacks(ctx, l.Org.ID, pkger.ListFilter{ - StackIDs: []influxdb.ID{newStack.ID}, + StackIDs: []platform.ID{newStack.ID}, }) require.NoError(t, err) @@ -696,7 +699,7 @@ func TestLauncher_Pkger(t *testing.T) { }) t.Run("apply a pkg with a stack and associations", func(t *testing.T) { - testLabelMappingFn := func(t *testing.T, stackID influxdb.ID, pkg *pkger.Template, assertAssociatedLabelsFn func(pkger.Summary, []*influxdb.Label, influxdb.ResourceType)) pkger.Summary { + testLabelMappingFn := func(t *testing.T, stackID platform.ID, pkg *pkger.Template, assertAssociatedLabelsFn func(pkger.Summary, []*influxdb.Label, influxdb.ResourceType)) pkger.Summary { t.Helper() impact, err := svc.Apply(ctx, l.Org.ID, l.User.ID, @@ -742,17 +745,17 @@ func TestLauncher_Pkger(t *testing.T) { assert.Equal(t, "tele-0", sum.TelegrafConfigs[0].TelegrafConfig.Name) resources := []struct { - resID influxdb.ID + resID platform.ID resourceType influxdb.ResourceType }{ - {resID: influxdb.ID(sum.Buckets[0].ID), resourceType: influxdb.BucketsResourceType}, + {resID: platform.ID(sum.Buckets[0].ID), resourceType: influxdb.BucketsResourceType}, {resID: sum.Checks[0].Check.GetID(), resourceType: influxdb.ChecksResourceType}, - {resID: influxdb.ID(sum.Dashboards[0].ID), resourceType: influxdb.DashboardsResourceType}, + {resID: platform.ID(sum.Dashboards[0].ID), resourceType: influxdb.DashboardsResourceType}, {resID: sum.NotificationEndpoints[0].NotificationEndpoint.GetID(), resourceType: influxdb.NotificationEndpointResourceType}, - {resID: influxdb.ID(sum.NotificationRules[0].ID), resourceType: influxdb.NotificationRuleResourceType}, - {resID: influxdb.ID(sum.Tasks[0].ID), resourceType: influxdb.TasksResourceType}, + {resID: platform.ID(sum.NotificationRules[0].ID), resourceType: influxdb.NotificationRuleResourceType}, + {resID: platform.ID(sum.Tasks[0].ID), resourceType: influxdb.TasksResourceType}, {resID: sum.TelegrafConfigs[0].TelegrafConfig.ID, resourceType: influxdb.TelegrafsResourceType}, - {resID: influxdb.ID(sum.Variables[0].ID), resourceType: influxdb.VariablesResourceType}, + {resID: platform.ID(sum.Variables[0].ID), resourceType: influxdb.VariablesResourceType}, } for _, res := range resources { mappedLabels, err := l.LabelService(t).FindResourceLabels(ctx, influxdb.LabelMappingFilter{ @@ -850,17 +853,17 @@ func TestLauncher_Pkger(t *testing.T) { require.Error(t, err) resources := []struct { - resID influxdb.ID + resID platform.ID resourceType influxdb.ResourceType }{ - {resID: influxdb.ID(sum.Buckets[0].ID), resourceType: influxdb.BucketsResourceType}, + {resID: platform.ID(sum.Buckets[0].ID), resourceType: influxdb.BucketsResourceType}, {resID: sum.Checks[0].Check.GetID(), resourceType: influxdb.ChecksResourceType}, - {resID: influxdb.ID(sum.Dashboards[0].ID), resourceType: influxdb.DashboardsResourceType}, + {resID: platform.ID(sum.Dashboards[0].ID), resourceType: influxdb.DashboardsResourceType}, {resID: sum.NotificationEndpoints[0].NotificationEndpoint.GetID(), resourceType: influxdb.NotificationEndpointResourceType}, - {resID: influxdb.ID(sum.NotificationRules[0].ID), resourceType: influxdb.NotificationRuleResourceType}, - {resID: influxdb.ID(sum.Tasks[0].ID), resourceType: influxdb.TasksResourceType}, + {resID: platform.ID(sum.NotificationRules[0].ID), resourceType: influxdb.NotificationRuleResourceType}, + {resID: platform.ID(sum.Tasks[0].ID), resourceType: influxdb.TasksResourceType}, {resID: sum.TelegrafConfigs[0].TelegrafConfig.ID, resourceType: influxdb.TelegrafsResourceType}, - {resID: influxdb.ID(sum.Variables[0].ID), resourceType: influxdb.VariablesResourceType}, + {resID: platform.ID(sum.Variables[0].ID), resourceType: influxdb.VariablesResourceType}, } for _, res := range resources { mappedLabels, err := l.LabelService(t).FindResourceLabels(ctx, influxdb.LabelMappingFilter{ @@ -1356,7 +1359,7 @@ func TestLauncher_Pkger(t *testing.T) { }) t.Run("apply should handle cases where users have changed platform data", func(t *testing.T) { - initializeStackPkg := func(t *testing.T, pkg *pkger.Template) (influxdb.ID, func(), pkger.Summary) { + initializeStackPkg := func(t *testing.T, pkg *pkger.Template) (platform.ID, func(), pkger.Summary) { t.Helper() stack, cleanup := newStackFn(t, pkger.StackCreate{}) @@ -1375,7 +1378,7 @@ func TestLauncher_Pkger(t *testing.T) { return stack.ID, cleanup, impact.Summary } - testValidRemoval := func(t *testing.T, stackID influxdb.ID) { + testValidRemoval := func(t *testing.T, stackID platform.ID) { t.Helper() _, err := svc.Apply( ctx, @@ -1387,7 +1390,7 @@ func TestLauncher_Pkger(t *testing.T) { } t.Run("when a user has deleted a variable that was previously created by a stack", func(t *testing.T) { - testUserDeletedVariable := func(t *testing.T, actionFn func(t *testing.T, stackID influxdb.ID, initialVarObj pkger.Object, initialSum pkger.Summary)) { + testUserDeletedVariable := func(t *testing.T, actionFn func(t *testing.T, stackID platform.ID, initialVarObj pkger.Object, initialSum pkger.Summary)) { t.Helper() obj := newVariableObject("var-1", "", "") @@ -1396,13 +1399,13 @@ func TestLauncher_Pkger(t *testing.T) { require.Len(t, initialSum.Variables, 1) require.NotZero(t, initialSum.Variables[0].ID) - resourceCheck.mustDeleteVariable(t, influxdb.ID(initialSum.Variables[0].ID)) + resourceCheck.mustDeleteVariable(t, platform.ID(initialSum.Variables[0].ID)) actionFn(t, stackID, obj, initialSum) } t.Run("should create new resource when attempting to update", func(t *testing.T) { - testUserDeletedVariable(t, func(t *testing.T, stackID influxdb.ID, initialVarObj pkger.Object, initialSum pkger.Summary) { + testUserDeletedVariable(t, func(t *testing.T, stackID platform.ID, initialVarObj pkger.Object, initialSum pkger.Summary) { pkg := newTemplate(initialVarObj) impact, err := svc.Apply(ctx, l.Org.ID, l.User.ID, pkger.ApplyWithTemplate(pkg), pkger.ApplyWithStackID(stackID)) require.NoError(t, err) @@ -1418,14 +1421,14 @@ func TestLauncher_Pkger(t *testing.T) { }) t.Run("should not error when attempting to remove", func(t *testing.T) { - testUserDeletedVariable(t, func(t *testing.T, stackID influxdb.ID, initialVarObj pkger.Object, initialSum pkger.Summary) { + testUserDeletedVariable(t, func(t *testing.T, stackID platform.ID, initialVarObj pkger.Object, initialSum pkger.Summary) { testValidRemoval(t, stackID) }) }) }) t.Run("when a user has deleted a bucket that was previously created by a stack", func(t *testing.T) { - testUserDeletedBucket := func(t *testing.T, actionFn func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary)) { + testUserDeletedBucket := func(t *testing.T, actionFn func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary)) { t.Helper() obj := newBucketObject("bucket-1", "", "") @@ -1434,13 +1437,13 @@ func TestLauncher_Pkger(t *testing.T) { require.Len(t, initialSum.Buckets, 1) require.NotZero(t, initialSum.Buckets[0].ID) - resourceCheck.mustDeleteBucket(t, influxdb.ID(initialSum.Buckets[0].ID)) + resourceCheck.mustDeleteBucket(t, platform.ID(initialSum.Buckets[0].ID)) actionFn(t, stackID, obj, initialSum) } t.Run("should create new resource when attempting to update", func(t *testing.T) { - testUserDeletedBucket(t, func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary) { + testUserDeletedBucket(t, func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary) { pkg := newTemplate(initialObj) impact, err := svc.Apply(ctx, l.Org.ID, l.User.ID, pkger.ApplyWithTemplate(pkg), pkger.ApplyWithStackID(stackID)) require.NoError(t, err) @@ -1456,14 +1459,14 @@ func TestLauncher_Pkger(t *testing.T) { }) t.Run("should not error when attempting to remove", func(t *testing.T) { - testUserDeletedBucket(t, func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary) { + testUserDeletedBucket(t, func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary) { testValidRemoval(t, stackID) }) }) }) t.Run("when a user has deleted a check that was previously created by a stack", func(t *testing.T) { - testUserDeletedCheck := func(t *testing.T, actionFn func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary)) { + testUserDeletedCheck := func(t *testing.T, actionFn func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary)) { t.Helper() obj := newCheckDeadmanObject(t, "check-1", "", time.Hour) @@ -1478,7 +1481,7 @@ func TestLauncher_Pkger(t *testing.T) { } t.Run("should create new resource when attempting to update", func(t *testing.T) { - testUserDeletedCheck(t, func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary) { + testUserDeletedCheck(t, func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary) { pkg := newTemplate(initialObj) impact, err := svc.Apply(ctx, l.Org.ID, l.User.ID, pkger.ApplyWithTemplate(pkg), pkger.ApplyWithStackID(stackID)) require.NoError(t, err) @@ -1495,14 +1498,14 @@ func TestLauncher_Pkger(t *testing.T) { }) t.Run("should not error when attempting to remove", func(t *testing.T) { - testUserDeletedCheck(t, func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary) { + testUserDeletedCheck(t, func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary) { testValidRemoval(t, stackID) }) }) }) t.Run("when a user has deleted a dashboard that was previously created by a stack", func(t *testing.T) { - testUserDeletedDashboard := func(t *testing.T, actionFn func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary)) { + testUserDeletedDashboard := func(t *testing.T, actionFn func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary)) { t.Helper() obj := newDashObject("dash-1", "", "") @@ -1511,13 +1514,13 @@ func TestLauncher_Pkger(t *testing.T) { require.Len(t, initialSum.Dashboards, 1) require.NotZero(t, initialSum.Dashboards[0].ID) - resourceCheck.mustDeleteDashboard(t, influxdb.ID(initialSum.Dashboards[0].ID)) + resourceCheck.mustDeleteDashboard(t, platform.ID(initialSum.Dashboards[0].ID)) actionFn(t, stackID, obj, initialSum) } t.Run("should create new resource when attempting to update", func(t *testing.T) { - testUserDeletedDashboard(t, func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary) { + testUserDeletedDashboard(t, func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary) { pkg := newTemplate(initialObj) impact, err := svc.Apply(ctx, l.Org.ID, l.User.ID, pkger.ApplyWithTemplate(pkg), pkger.ApplyWithStackID(stackID)) require.NoError(t, err) @@ -1533,14 +1536,14 @@ func TestLauncher_Pkger(t *testing.T) { }) t.Run("should not error when attempting to remove", func(t *testing.T) { - testUserDeletedDashboard(t, func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary) { + testUserDeletedDashboard(t, func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary) { testValidRemoval(t, stackID) }) }) }) t.Run("when a user has deleted a label that was previously created by a stack", func(t *testing.T) { - testUserDeletedLabel := func(t *testing.T, actionFn func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary)) { + testUserDeletedLabel := func(t *testing.T, actionFn func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary)) { t.Helper() obj := newLabelObject("label-1", "", "", "") @@ -1549,13 +1552,13 @@ func TestLauncher_Pkger(t *testing.T) { require.Len(t, initialSum.Labels, 1) require.NotZero(t, initialSum.Labels[0].ID) - resourceCheck.mustDeleteLabel(t, influxdb.ID(initialSum.Labels[0].ID)) + resourceCheck.mustDeleteLabel(t, platform.ID(initialSum.Labels[0].ID)) actionFn(t, stackID, obj, initialSum) } t.Run("should create new resource when attempting to update", func(t *testing.T) { - testUserDeletedLabel(t, func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary) { + testUserDeletedLabel(t, func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary) { pkg := newTemplate(initialObj) impact, err := svc.Apply(ctx, l.Org.ID, l.User.ID, pkger.ApplyWithTemplate(pkg), pkger.ApplyWithStackID(stackID)) require.NoError(t, err) @@ -1571,14 +1574,14 @@ func TestLauncher_Pkger(t *testing.T) { }) t.Run("should not error when attempting to remove", func(t *testing.T) { - testUserDeletedLabel(t, func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary) { + testUserDeletedLabel(t, func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary) { testValidRemoval(t, stackID) }) }) }) t.Run("when a user has deleted a notification endpoint that was previously created by a stack", func(t *testing.T) { - testUserDeletedEndpoint := func(t *testing.T, actionFn func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary)) { + testUserDeletedEndpoint := func(t *testing.T, actionFn func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary)) { t.Helper() obj := newEndpointHTTP("endpoint-1", "", "") @@ -1593,7 +1596,7 @@ func TestLauncher_Pkger(t *testing.T) { } t.Run("should create new resource when attempting to update", func(t *testing.T) { - testUserDeletedEndpoint(t, func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary) { + testUserDeletedEndpoint(t, func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary) { pkg := newTemplate(initialObj) impact, err := svc.Apply(ctx, l.Org.ID, l.User.ID, pkger.ApplyWithTemplate(pkg), pkger.ApplyWithStackID(stackID)) require.NoError(t, err) @@ -1610,14 +1613,14 @@ func TestLauncher_Pkger(t *testing.T) { }) t.Run("should not error when attempting to remove", func(t *testing.T) { - testUserDeletedEndpoint(t, func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary) { + testUserDeletedEndpoint(t, func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary) { testValidRemoval(t, stackID) }) }) }) t.Run("when a user has deleted a notification rule that was previously created by a stack", func(t *testing.T) { - testUserDeletedRule := func(t *testing.T, actionFn func(t *testing.T, stackID influxdb.ID, initialObjects []pkger.Object, initialSum pkger.Summary)) { + testUserDeletedRule := func(t *testing.T, actionFn func(t *testing.T, stackID platform.ID, initialObjects []pkger.Object, initialSum pkger.Summary)) { t.Helper() endpointObj := newEndpointHTTP("endpoint-1", "", "") @@ -1629,13 +1632,13 @@ func TestLauncher_Pkger(t *testing.T) { require.NotZero(t, initialSum.NotificationEndpoints[0].NotificationEndpoint.GetID()) require.Len(t, initialSum.NotificationRules, 1) require.NotZero(t, initialSum.NotificationRules[0].ID) - resourceCheck.mustDeleteRule(t, influxdb.ID(initialSum.NotificationRules[0].ID)) + resourceCheck.mustDeleteRule(t, platform.ID(initialSum.NotificationRules[0].ID)) actionFn(t, stackID, []pkger.Object{ruleObj, endpointObj}, initialSum) } t.Run("should create new resource when attempting to update", func(t *testing.T) { - testUserDeletedRule(t, func(t *testing.T, stackID influxdb.ID, initialObjects []pkger.Object, initialSum pkger.Summary) { + testUserDeletedRule(t, func(t *testing.T, stackID platform.ID, initialObjects []pkger.Object, initialSum pkger.Summary) { pkg := newTemplate(initialObjects...) impact, err := svc.Apply(ctx, l.Org.ID, l.User.ID, pkger.ApplyWithTemplate(pkg), pkger.ApplyWithStackID(stackID)) require.NoError(t, err) @@ -1651,14 +1654,14 @@ func TestLauncher_Pkger(t *testing.T) { }) t.Run("should not error when attempting to remove", func(t *testing.T) { - testUserDeletedRule(t, func(t *testing.T, stackID influxdb.ID, _ []pkger.Object, _ pkger.Summary) { + testUserDeletedRule(t, func(t *testing.T, stackID platform.ID, _ []pkger.Object, _ pkger.Summary) { testValidRemoval(t, stackID) }) }) }) t.Run("when a user has deleted a task that was previously created by a stack", func(t *testing.T) { - testUserDeletedTask := func(t *testing.T, actionFn func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary)) { + testUserDeletedTask := func(t *testing.T, actionFn func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary)) { t.Helper() obj := newTaskObject("task-1", "", "") @@ -1667,13 +1670,13 @@ func TestLauncher_Pkger(t *testing.T) { require.Len(t, initialSum.Tasks, 1) require.NotZero(t, initialSum.Tasks[0].ID) - resourceCheck.mustDeleteTask(t, influxdb.ID(initialSum.Tasks[0].ID)) + resourceCheck.mustDeleteTask(t, platform.ID(initialSum.Tasks[0].ID)) actionFn(t, stackID, obj, initialSum) } t.Run("should create new resource when attempting to update", func(t *testing.T) { - testUserDeletedTask(t, func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary) { + testUserDeletedTask(t, func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary) { pkg := newTemplate(initialObj) impact, err := svc.Apply(ctx, l.Org.ID, l.User.ID, pkger.ApplyWithTemplate(pkg), pkger.ApplyWithStackID(stackID)) require.NoError(t, err) @@ -1689,14 +1692,14 @@ func TestLauncher_Pkger(t *testing.T) { }) t.Run("should not error when attempting to remove", func(t *testing.T) { - testUserDeletedTask(t, func(t *testing.T, stackID influxdb.ID, _ pkger.Object, _ pkger.Summary) { + testUserDeletedTask(t, func(t *testing.T, stackID platform.ID, _ pkger.Object, _ pkger.Summary) { testValidRemoval(t, stackID) }) }) }) t.Run("when a user has deleted a telegraf config that was previously created by a stack", func(t *testing.T) { - testUserDeletedTelegraf := func(t *testing.T, actionFn func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary)) { + testUserDeletedTelegraf := func(t *testing.T, actionFn func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary)) { t.Helper() obj := newTelegrafObject("tele-1", "", "") @@ -1711,7 +1714,7 @@ func TestLauncher_Pkger(t *testing.T) { } t.Run("should create new resource when attempting to update", func(t *testing.T) { - testUserDeletedTelegraf(t, func(t *testing.T, stackID influxdb.ID, initialObj pkger.Object, initialSum pkger.Summary) { + testUserDeletedTelegraf(t, func(t *testing.T, stackID platform.ID, initialObj pkger.Object, initialSum pkger.Summary) { pkg := newTemplate(initialObj) impact, err := svc.Apply(ctx, l.Org.ID, l.User.ID, pkger.ApplyWithTemplate(pkg), pkger.ApplyWithStackID(stackID)) require.NoError(t, err) @@ -1727,7 +1730,7 @@ func TestLauncher_Pkger(t *testing.T) { }) t.Run("should not error when attempting to remove", func(t *testing.T) { - testUserDeletedTelegraf(t, func(t *testing.T, stackID influxdb.ID, _ pkger.Object, _ pkger.Summary) { + testUserDeletedTelegraf(t, func(t *testing.T, stackID platform.ID, _ pkger.Object, _ pkger.Summary) { testValidRemoval(t, stackID) }) }) @@ -1746,7 +1749,7 @@ func TestLauncher_Pkger(t *testing.T) { vars := impact.Summary.Variables require.Len(t, vars, 1) - v := resourceCheck.mustGetVariable(t, byID(influxdb.ID(vars[0].ID))) + v := resourceCheck.mustGetVariable(t, byID(platform.ID(vars[0].ID))) assert.Empty(t, v.Selected) impact, err = svc.Apply(ctx, l.Org.ID, l.User.ID, @@ -1757,7 +1760,7 @@ func TestLauncher_Pkger(t *testing.T) { vars = impact.Summary.Variables require.Len(t, vars, 1) - v = resourceCheck.mustGetVariable(t, byID(influxdb.ID(vars[0].ID))) + v = resourceCheck.mustGetVariable(t, byID(platform.ID(vars[0].ID))) assert.Equal(t, []string{"selected"}, v.Selected) }) @@ -2250,8 +2253,8 @@ func TestLauncher_Pkger(t *testing.T) { defer cleanup() err := l.LabelService(t).DeleteLabelMapping(ctx, &influxdb.LabelMapping{ - LabelID: influxdb.ID(initialSummary.Labels[0].ID), - ResourceID: influxdb.ID(initialSummary.Buckets[0].ID), + LabelID: platform.ID(initialSummary.Labels[0].ID), + ResourceID: platform.ID(initialSummary.Buckets[0].ID), ResourceType: influxdb.BucketsResourceType, }) require.NoError(t, err) @@ -2278,7 +2281,7 @@ func TestLauncher_Pkger(t *testing.T) { err := l.LabelService(t).CreateLabelMapping(ctx, &influxdb.LabelMapping{ LabelID: newLabel.ID, - ResourceID: influxdb.ID(initialSummary.Buckets[0].ID), + ResourceID: platform.ID(initialSummary.Buckets[0].ID), ResourceType: influxdb.BucketsResourceType, }) require.NoError(t, err) @@ -2987,7 +2990,7 @@ spec: Query: "buckets() |> filter(fn: (r) => r.name !~ /^_/) |> rename(columns: {name: \"_value\"}) |> keep(columns: [\"_value\"])", Language: "flux", }, varArgs.Values) - platformVar := resourceCheck.mustGetVariable(t, byID(influxdb.ID(vars[0].ID))) + platformVar := resourceCheck.mustGetVariable(t, byID(platform.ID(vars[0].ID))) assert.Equal(t, []string{"rucketeer"}, platformVar.Selected) newSumMapping := func(id pkger.SafeID, pkgName, name string, rt influxdb.ResourceType) pkger.SummaryLabelMapping { @@ -3301,7 +3304,7 @@ spec: resToClone := []pkger.ResourceToClone{ { Kind: pkger.KindBucket, - ID: influxdb.ID(sum1Bkts[0].ID), + ID: platform.ID(sum1Bkts[0].ID), }, { Kind: pkger.KindCheck, @@ -3313,11 +3316,11 @@ spec: }, { Kind: pkger.KindDashboard, - ID: influxdb.ID(sum1Dashs[0].ID), + ID: platform.ID(sum1Dashs[0].ID), }, { Kind: pkger.KindLabel, - ID: influxdb.ID(sum1Labels[0].ID), + ID: platform.ID(sum1Labels[0].ID), }, { Kind: pkger.KindNotificationEndpoint, @@ -3325,7 +3328,7 @@ spec: }, { Kind: pkger.KindTask, - ID: influxdb.ID(sum1Tasks[0].ID), + ID: platform.ID(sum1Tasks[0].ID), }, { Kind: pkger.KindTelegraf, @@ -3337,12 +3340,12 @@ spec: { Kind: pkger.KindNotificationRule, Name: "new rule name", - ID: influxdb.ID(sum1Rules[0].ID), + ID: platform.ID(sum1Rules[0].ID), }, { Kind: pkger.KindVariable, Name: "new name", - ID: influxdb.ID(sum1Vars[0].ID), + ID: platform.ID(sum1Vars[0].ID), }, } @@ -3450,7 +3453,7 @@ spec: _, err = svc.Apply(ctx, l.Org.ID, 0, pkger.ApplyWithTemplate(updatePkg)) require.Error(t, err) - bkt, err := l.BucketService(t).FindBucketByID(ctx, influxdb.ID(sum1Bkts[0].ID)) + bkt, err := l.BucketService(t).FindBucketByID(ctx, platform.ID(sum1Bkts[0].ID)) require.NoError(t, err) // make sure the desc change is not applied and is rolled back to prev desc assert.Equal(t, sum1Bkts[0].Description, bkt.Description) @@ -3465,7 +3468,7 @@ spec: // direct comparison very annoying... assert.Equal(t, sum1Checks[0].Check.(*check.Threshold).Query.Text, deadman.Query.Text) - label, err := l.LabelService(t).FindLabelByID(ctx, influxdb.ID(sum1Labels[0].ID)) + label, err := l.LabelService(t).FindLabelByID(ctx, platform.ID(sum1Labels[0].ID)) require.NoError(t, err) assert.Equal(t, sum1Labels[0].Properties.Description, label.Properties["description"]) @@ -3473,7 +3476,7 @@ spec: require.NoError(t, err) assert.Equal(t, sum1Endpoints[0].NotificationEndpoint.GetDescription(), endpoint.GetDescription()) - v, err := l.VariableService(t).FindVariableByID(ctx, influxdb.ID(sum1Vars[0].ID)) + v, err := l.VariableService(t).FindVariableByID(ctx, platform.ID(sum1Vars[0].ID)) require.NoError(t, err) assert.Equal(t, sum1Vars[0].Description, v.Description) }) @@ -3569,7 +3572,7 @@ spec: require.NotZero(t, impact.Summary.Buckets[0].ID) stacks, err := svc.ListStacks(ctx, l.Org.ID, pkger.ListFilter{ - StackIDs: []influxdb.ID{impact.StackID}, + StackIDs: []platform.ID{impact.StackID}, }) require.NoError(t, err) @@ -3577,7 +3580,7 @@ spec: ev := stacks[0].LatestEvent() require.Len(t, ev.Resources, 1) assert.Equal(t, ev.Resources[0].MetaName, "room") - assert.Equal(t, influxdb.ID(impact.Summary.Buckets[0].ID), ev.Resources[0].ID) + assert.Equal(t, platform.ID(impact.Summary.Buckets[0].ID), ev.Resources[0].ID) }) t.Run("apply a template with env refs", func(t *testing.T) { @@ -4579,7 +4582,7 @@ func (f *fakeBucketSVC) CreateBucket(ctx context.Context, b *influxdb.Bucket) er return f.BucketService.CreateBucket(ctx, b) } -func (f *fakeBucketSVC) UpdateBucket(ctx context.Context, id influxdb.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { +func (f *fakeBucketSVC) UpdateBucket(ctx context.Context, id platform.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { defer f.updateCallCount.IncrFn()() if f.updateCallCount.Count() == f.updateKillCount { return nil, errors.New("reached kill count") @@ -4618,7 +4621,7 @@ type fakeRuleStore struct { createKillCount int } -func (f *fakeRuleStore) CreateNotificationRule(ctx context.Context, nr influxdb.NotificationRuleCreate, userID influxdb.ID) error { +func (f *fakeRuleStore) CreateNotificationRule(ctx context.Context, nr influxdb.NotificationRuleCreate, userID platform.ID) error { defer f.createCallCount.IncrFn()() if f.createCallCount.Count() == f.createKillCount { return errors.New("reached kill count") @@ -4629,7 +4632,7 @@ func (f *fakeRuleStore) CreateNotificationRule(ctx context.Context, nr influxdb. func assertErrorCode(t *testing.T, expected string, err error) { t.Helper() assert.Error(t, err) - assert.Equal(t, expected, influxdb.ErrorCode(err)) + assert.Equal(t, expected, errors2.ErrorCode(err)) } type resourceChecker struct { @@ -4642,14 +4645,14 @@ func newResourceChecker(tl *TestLauncher) resourceChecker { type ( getResourceOpt struct { - id influxdb.ID + id platform.ID name string } getResourceOptFn func() getResourceOpt ) -func byID(id influxdb.ID) getResourceOptFn { +func byID(id platform.ID) getResourceOptFn { return func() getResourceOpt { return getResourceOpt{id: id} } @@ -4663,7 +4666,7 @@ func byName(name string) getResourceOptFn { func bySafeID(id pkger.SafeID) getResourceOptFn { return func() getResourceOpt { - return getResourceOpt{id: influxdb.ID(id)} + return getResourceOpt{id: platform.ID(id)} } } @@ -4699,7 +4702,7 @@ func (r resourceChecker) mustGetBucket(t *testing.T, getOpt getResourceOptFn) in return bkt } -func (r resourceChecker) mustDeleteBucket(t *testing.T, id influxdb.ID) { +func (r resourceChecker) mustDeleteBucket(t *testing.T, id platform.ID) { t.Helper() require.NoError(t, r.tl.BucketService(t).DeleteBucket(ctx, id)) } @@ -4736,7 +4739,7 @@ func (r resourceChecker) mustGetCheck(t *testing.T, getOpt getResourceOptFn) inf return c } -func (r resourceChecker) mustDeleteCheck(t *testing.T, id influxdb.ID) { +func (r resourceChecker) mustDeleteCheck(t *testing.T, id platform.ID) { t.Helper() require.NoError(t, r.tl.CheckService().DeleteCheck(ctx, id)) @@ -4787,7 +4790,7 @@ func (r resourceChecker) mustGetDashboard(t *testing.T, getOpt getResourceOptFn) return dash } -func (r resourceChecker) mustDeleteDashboard(t *testing.T, id influxdb.ID) { +func (r resourceChecker) mustDeleteDashboard(t *testing.T, id platform.ID) { t.Helper() require.NoError(t, r.tl.DashboardService(t).DeleteDashboard(ctx, id)) @@ -4835,7 +4838,7 @@ func (r resourceChecker) mustGetEndpoint(t *testing.T, getOpt getResourceOptFn) return e } -func (r resourceChecker) mustDeleteEndpoint(t *testing.T, id influxdb.ID) { +func (r resourceChecker) mustDeleteEndpoint(t *testing.T, id platform.ID) { t.Helper() _, _, err := r.tl.NotificationEndpointService(t).DeleteNotificationEndpoint(ctx, id) @@ -4888,7 +4891,7 @@ func (r resourceChecker) mustGetLabel(t *testing.T, getOpt getResourceOptFn) inf return l } -func (r resourceChecker) mustDeleteLabel(t *testing.T, id influxdb.ID) { +func (r resourceChecker) mustDeleteLabel(t *testing.T, id platform.ID) { t.Helper() require.NoError(t, r.tl.LabelService(t).DeleteLabel(ctx, id)) } @@ -4935,7 +4938,7 @@ func (r resourceChecker) mustGetRule(t *testing.T, getOpt getResourceOptFn) infl return rule } -func (r resourceChecker) mustDeleteRule(t *testing.T, id influxdb.ID) { +func (r resourceChecker) mustDeleteRule(t *testing.T, id platform.ID) { t.Helper() require.NoError(t, r.tl.NotificationRuleService(t).DeleteNotificationRule(ctx, id)) @@ -4985,7 +4988,7 @@ func (r resourceChecker) mustGetTask(t *testing.T, getOpt getResourceOptFn) infl return task } -func (r resourceChecker) mustDeleteTask(t *testing.T, id influxdb.ID) { +func (r resourceChecker) mustDeleteTask(t *testing.T, id platform.ID) { t.Helper() require.NoError(t, r.tl.TaskService(t).DeleteTask(ctx, id)) @@ -5031,7 +5034,7 @@ func (r resourceChecker) mustGetTelegrafConfig(t *testing.T, getOpt getResourceO return tele } -func (r resourceChecker) mustDeleteTelegrafConfig(t *testing.T, id influxdb.ID) { +func (r resourceChecker) mustDeleteTelegrafConfig(t *testing.T, id platform.ID) { t.Helper() require.NoError(t, r.tl.TelegrafService(t).DeleteTelegrafConfig(ctx, id)) @@ -5083,7 +5086,7 @@ func (r resourceChecker) mustGetVariable(t *testing.T, getOpt getResourceOptFn) return l } -func (r resourceChecker) mustDeleteVariable(t *testing.T, id influxdb.ID) { +func (r resourceChecker) mustDeleteVariable(t *testing.T, id platform.ID) { t.Helper() err := r.tl.VariableService(t).DeleteVariable(ctx, id) diff --git a/cmd/influxd/launcher/print_config_test.go b/cmd/influxd/launcher/print_config_test.go index f8f28e63299..e56771bc330 100644 --- a/cmd/influxd/launcher/print_config_test.go +++ b/cmd/influxd/launcher/print_config_test.go @@ -4,7 +4,8 @@ import ( "bytes" "testing" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/cli" "github.com/stretchr/testify/require" "go.uber.org/zap/zapcore" @@ -19,7 +20,7 @@ var floatVar = 987.654 var sliceVar = []string{"hello", "world"} var mapVar = map[string]string{"foo": "bar", "baz": "qux"} var levelVar = zapcore.InfoLevel -var idVar, _ = influxdb.IDFromString("020f755c3c082000") +var idVar, _ = platform.IDFromString("020f755c3c082000") var opts = []cli.Opt{ { diff --git a/cmd/influxd/launcher/query_test.go b/cmd/influxd/launcher/query_test.go index 251b31ad502..139b00e63a3 100644 --- a/cmd/influxd/launcher/query_test.go +++ b/cmd/influxd/launcher/query_test.go @@ -5,6 +5,7 @@ import ( "context" "errors" "fmt" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" "html/template" "io" "io/ioutil" @@ -590,7 +591,7 @@ from(bucket: "%s") } if err := l.QueryAndNopConsume(ctx, req); err == nil { t.Error("expected error") - } else if got, want := influxdb.ErrorCode(err), influxdb.EUnauthorized; got != want { + } else if got, want := errors2.ErrorCode(err), errors2.EUnauthorized; got != want { t.Errorf("unexpected error code -want/+got:\n\t- %v\n\t+ %v", got, want) } } diff --git a/cmd/influxd/upgrade/database.go b/cmd/influxd/upgrade/database.go index 79fc27304f8..788c39b2e80 100644 --- a/cmd/influxd/upgrade/database.go +++ b/cmd/influxd/upgrade/database.go @@ -8,6 +8,8 @@ import ( "path/filepath" "strings" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/dustin/go-humanize" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/cmd/internal" @@ -18,10 +20,10 @@ import ( ) // upgradeDatabases creates databases, buckets, retention policies and shard info according to 1.x meta and copies data -func upgradeDatabases(ctx context.Context, ui *input.UI, v1 *influxDBv1, v2 *influxDBv2, opts *options, orgID influxdb.ID, log *zap.Logger) (map[string][]influxdb.ID, error) { +func upgradeDatabases(ctx context.Context, ui *input.UI, v1 *influxDBv1, v2 *influxDBv2, opts *options, orgID platform.ID, log *zap.Logger) (map[string][]platform.ID, error) { v1opts := opts.source v2opts := opts.target - db2BucketIds := make(map[string][]influxdb.ID) + db2BucketIds := make(map[string][]platform.ID) targetDataPath := filepath.Join(v2opts.enginePath, "data") targetWalPath := filepath.Join(v2opts.enginePath, "wal") @@ -61,7 +63,7 @@ func upgradeDatabases(ctx context.Context, ui *input.UI, v1 *influxDBv1, v2 *inf log.Debug("Upgrading database", zap.String("database", db.Name)) // db to buckets IDs mapping - db2BucketIds[db.Name] = make([]influxdb.ID, 0, len(db.RetentionPolicies)) + db2BucketIds[db.Name] = make([]platform.ID, 0, len(db.RetentionPolicies)) for _, rp := range db.RetentionPolicies { sourcePath := filepath.Join(v1opts.dataDir, db.Name, rp.Name) diff --git a/cmd/influxd/upgrade/security.go b/cmd/influxd/upgrade/security.go index 220ac6a56e8..d8597e51198 100644 --- a/cmd/influxd/upgrade/security.go +++ b/cmd/influxd/upgrade/security.go @@ -9,6 +9,8 @@ import ( "fmt" "sort" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/v1/services/meta" "github.com/influxdata/influxql" @@ -21,7 +23,7 @@ func upgradeUsers( v1 *influxDBv1, v2 *influxDBv2, targetOptions *optionsV2, - dbBuckets map[string][]platform.ID, + dbBuckets map[string][]platform2.ID, log *zap.Logger, ) (int, error) { // check if there any 1.x users at all @@ -128,7 +130,7 @@ func newSecurityUpgradeHelper(log *zap.Logger) *securityUpgradeHelper { return helper } -func (h *securityUpgradeHelper) checkDbBuckets(meta *meta.Client, databases map[string][]platform.ID) bool { +func (h *securityUpgradeHelper) checkDbBuckets(meta *meta.Client, databases map[string][]platform2.ID) bool { ok := true for _, row := range meta.Users() { for database := range row.Privileges { diff --git a/cmd/influxd/upgrade/security_test.go b/cmd/influxd/upgrade/security_test.go index cee8cba0e80..41f6611fbdb 100644 --- a/cmd/influxd/upgrade/security_test.go +++ b/cmd/influxd/upgrade/security_test.go @@ -8,6 +8,8 @@ import ( "testing" "unsafe" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/authorization" @@ -30,7 +32,7 @@ func TestUpgradeSecurity(t *testing.T) { type testCase struct { name string users []meta.UserInfo - db2ids map[string][]influxdb.ID + db2ids map[string][]platform.ID wantErr error want []*influxdb.Authorization } @@ -90,7 +92,7 @@ func TestUpgradeSecurity(t *testing.T) { }, }, }, - db2ids: map[string][]influxdb.ID{ + db2ids: map[string][]platform.ID{ "water": {0x33f9d67bc9cbc5b7, 0x33f9d67bc9cbc5b8, 0x33f9d67bc9cbc5b9}, "air": {0x43f9d67bc9cbc5b7, 0x43f9d67bc9cbc5b8, 0x43f9d67bc9cbc5b9}, "hits": {0x53f9d67bc9cbc5b7}, diff --git a/cmd/influxd/upgrade/upgrade.go b/cmd/influxd/upgrade/upgrade.go index ea0372011d6..396ced0bc6d 100644 --- a/cmd/influxd/upgrade/upgrade.go +++ b/cmd/influxd/upgrade/upgrade.go @@ -11,6 +11,8 @@ import ( "path/filepath" "strings" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/authorization" "github.com/influxdata/influxdb/v2/bolt" @@ -98,8 +100,8 @@ type optionsV2 struct { password string orgName string bucket string - orgID influxdb.ID - userID influxdb.ID + orgID platform.ID + userID platform.ID token string retention string } diff --git a/context/token.go b/context/token.go index 00f265712cf..e516cc3fcab 100644 --- a/context/token.go +++ b/context/token.go @@ -4,6 +4,9 @@ import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) @@ -22,14 +25,14 @@ func SetAuthorizer(ctx context.Context, a influxdb.Authorizer) context.Context { func GetAuthorizer(ctx context.Context) (influxdb.Authorizer, error) { a, ok := ctx.Value(authorizerCtxKey).(influxdb.Authorizer) if !ok { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Msg: "authorizer not found on context", - Code: influxdb.EInternal, + Code: errors.EInternal, } } if a == nil { - return nil, &influxdb.Error{ - Code: influxdb.EInternal, + return nil, &errors.Error{ + Code: errors.EInternal, Msg: "unexpected invalid authorizer", } } @@ -41,17 +44,17 @@ func GetAuthorizer(ctx context.Context) (influxdb.Authorizer, error) { func GetToken(ctx context.Context) (string, error) { a, ok := ctx.Value(authorizerCtxKey).(influxdb.Authorizer) if !ok { - return "", &influxdb.Error{ + return "", &errors.Error{ Msg: "authorizer not found on context", - Code: influxdb.EInternal, + Code: errors.EInternal, } } auth, ok := a.(*influxdb.Authorization) if !ok { - return "", &influxdb.Error{ + return "", &errors.Error{ Msg: fmt.Sprintf("authorizer not an authorization but a %T", a), - Code: influxdb.EInternal, + Code: errors.EInternal, } } @@ -59,7 +62,7 @@ func GetToken(ctx context.Context) (string, error) { } // GetUserID retrieves the user ID from the authorizer on the context. -func GetUserID(ctx context.Context) (influxdb.ID, error) { +func GetUserID(ctx context.Context) (platform.ID, error) { a, err := GetAuthorizer(ctx) if err != nil { return 0, err diff --git a/context/token_test.go b/context/token_test.go index f61b5621e24..1700d736f5b 100644 --- a/context/token_test.go +++ b/context/token_test.go @@ -2,6 +2,7 @@ package context_test import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" "testing" "github.com/influxdata/influxdb/v2" @@ -18,7 +19,7 @@ func TestGetAuthorizer(t *testing.T) { t.Errorf("unexpected error while retrieving token: %v", err) } - if want := influxdb.ID(1234); got.Identifier() != want { + if want := platform.ID(1234); got.Identifier() != want { t.Errorf("GetToken() want %s, got %s", want, got) } } @@ -48,7 +49,7 @@ func TestGetUserID(t *testing.T) { t.Errorf("unexpected error while retrieving user ID: %v", err) } - if want := influxdb.ID(5678); got != want { + if want := platform.ID(5678); got != want { t.Errorf("GetUserID() want %s, got %s", want, got) } } diff --git a/credentials.go b/credentials.go index d724a313461..e9fe541d2fe 100644 --- a/credentials.go +++ b/credentials.go @@ -1,12 +1,16 @@ package influxdb -import "context" +import ( + "context" + + "github.com/influxdata/influxdb/v2/kit/platform/errors" +) var ( // ErrCredentialsUnauthorized is the error returned when CredentialsV1 cannot be // authorized. - ErrCredentialsUnauthorized = &Error{ - Code: EUnauthorized, + ErrCredentialsUnauthorized = &errors.Error{ + Code: errors.EUnauthorized, Msg: "Unauthorized", } ) diff --git a/dashboard.go b/dashboard.go index c05463b43f4..471ddb92e35 100644 --- a/dashboard.go +++ b/dashboard.go @@ -7,6 +7,9 @@ import ( "net/url" "sort" "time" + + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) // ErrDashboardNotFound is the error msg for a missing dashboard. @@ -36,7 +39,7 @@ const ( // DashboardService represents a service for managing dashboard data. type DashboardService interface { // FindDashboardByID returns a single dashboard by ID. - FindDashboardByID(ctx context.Context, id ID) (*Dashboard, error) + FindDashboardByID(ctx context.Context, id platform.ID) (*Dashboard, error) // FindDashboards returns a list of dashboards that match filter and the total count of matching dashboards. // Additional options provide pagination & sorting. @@ -47,39 +50,39 @@ type DashboardService interface { // UpdateDashboard updates a single dashboard with changeset. // Returns the new dashboard state after update. - UpdateDashboard(ctx context.Context, id ID, upd DashboardUpdate) (*Dashboard, error) + UpdateDashboard(ctx context.Context, id platform.ID, upd DashboardUpdate) (*Dashboard, error) // AddDashboardCell adds a cell to a dashboard. - AddDashboardCell(ctx context.Context, id ID, c *Cell, opts AddDashboardCellOptions) error + AddDashboardCell(ctx context.Context, id platform.ID, c *Cell, opts AddDashboardCellOptions) error // RemoveDashboardCell removes a dashboard. - RemoveDashboardCell(ctx context.Context, dashboardID, cellID ID) error + RemoveDashboardCell(ctx context.Context, dashboardID, cellID platform.ID) error // UpdateDashboardCell replaces the dashboard cell with the provided ID. - UpdateDashboardCell(ctx context.Context, dashboardID, cellID ID, upd CellUpdate) (*Cell, error) + UpdateDashboardCell(ctx context.Context, dashboardID, cellID platform.ID, upd CellUpdate) (*Cell, error) // GetDashboardCellView retrieves a dashboard cells view. - GetDashboardCellView(ctx context.Context, dashboardID, cellID ID) (*View, error) + GetDashboardCellView(ctx context.Context, dashboardID, cellID platform.ID) (*View, error) // UpdateDashboardCellView retrieves a dashboard cells view. - UpdateDashboardCellView(ctx context.Context, dashboardID, cellID ID, upd ViewUpdate) (*View, error) + UpdateDashboardCellView(ctx context.Context, dashboardID, cellID platform.ID, upd ViewUpdate) (*View, error) // DeleteDashboard removes a dashboard by ID. - DeleteDashboard(ctx context.Context, id ID) error + DeleteDashboard(ctx context.Context, id platform.ID) error // ReplaceDashboardCells replaces all cells in a dashboard - ReplaceDashboardCells(ctx context.Context, id ID, c []*Cell) error + ReplaceDashboardCells(ctx context.Context, id platform.ID, c []*Cell) error } // Dashboard represents all visual and query data for a dashboard. type Dashboard struct { - ID ID `json:"id,omitempty"` - OrganizationID ID `json:"orgID,omitempty"` + ID platform.ID `json:"id,omitempty"` + OrganizationID platform.ID `json:"orgID,omitempty"` Name string `json:"name"` Description string `json:"description"` Cells []*Cell `json:"cells"` Meta DashboardMeta `json:"meta"` - OwnerID *ID `json:"owner,omitempty"` + OwnerID *platform.ID `json:"owner,omitempty"` } // DashboardMeta contains meta information about dashboards @@ -123,7 +126,7 @@ func SortDashboards(opts FindOptions, ds []*Dashboard) { // Cell holds positional information about a cell on dashboard and a reference to a cell. type Cell struct { - ID ID `json:"id,omitempty"` + ID platform.ID `json:"id,omitempty"` CellProperty View *View `json:"-"` } @@ -131,7 +134,7 @@ type Cell struct { // Marshals the cell func (c *Cell) MarshalJSON() ([]byte, error) { type resp struct { - ID *ID `json:"id,omitempty"` + ID *platform.ID `json:"id,omitempty"` Name string `json:"name,omitempty"` ViewProperties json.RawMessage `json:"properties,omitempty"` CellProperty @@ -155,7 +158,7 @@ func (c *Cell) MarshalJSON() ([]byte, error) { func (c *Cell) UnmarshalJSON(b []byte) error { var newCell struct { - ID ID `json:"id,omitempty"` + ID platform.ID `json:"id,omitempty"` Name string `json:"name,omitempty"` ViewProperties json.RawMessage `json:"properties,omitempty"` CellProperty @@ -195,10 +198,10 @@ type CellProperty struct { // DashboardFilter is a filter for dashboards. type DashboardFilter struct { - IDs []*ID - OrganizationID *ID + IDs []*platform.ID + OrganizationID *platform.ID Organization *string - OwnerID *ID + OwnerID *platform.ID } // QueryParams turns a dashboard filter into query params @@ -252,10 +255,10 @@ func (u DashboardUpdate) Apply(d *Dashboard) error { } // Valid returns an error if the dashboard update is invalid. -func (u DashboardUpdate) Valid() *Error { +func (u DashboardUpdate) Valid() *errors.Error { if u.Name == nil && u.Description == nil { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "must update at least one attribute", } } @@ -298,10 +301,10 @@ func (u CellUpdate) Apply(c *Cell) error { } // Valid returns an error if the cell update is invalid. -func (u CellUpdate) Valid() *Error { +func (u CellUpdate) Valid() *errors.Error { if u.H == nil && u.W == nil && u.Y == nil && u.X == nil { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "must update at least one attribute", } } @@ -316,11 +319,11 @@ type ViewUpdate struct { } // Valid validates the update struct. It expects minimal values to be set. -func (u ViewUpdate) Valid() *Error { +func (u ViewUpdate) Valid() *errors.Error { _, ok := u.Properties.(EmptyViewProperties) if u.Name == nil && ok { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "expected at least one attribute to be updated", } } @@ -352,7 +355,7 @@ type ViewContentsUpdate struct { // ViewFilter represents a set of filter that restrict the returned results. type ViewFilter struct { - ID *ID + ID *platform.ID Types []string } @@ -364,8 +367,8 @@ type View struct { // ViewContents is the id and name of a specific view. type ViewContents struct { - ID ID `json:"id,omitempty"` - Name string `json:"name"` + ID platform.ID `json:"id,omitempty"` + Name string `json:"name"` } // Values for all supported view property types. diff --git a/dashboards/service.go b/dashboards/service.go index b1e782e2755..4d3fa99e6e1 100644 --- a/dashboards/service.go +++ b/dashboards/service.go @@ -6,6 +6,9 @@ import ( "encoding/json" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + influxdb "github.com/influxdata/influxdb/v2" icontext "github.com/influxdata/influxdb/v2/context" "github.com/influxdata/influxdb/v2/kit/feature" @@ -46,7 +49,7 @@ type Service struct { opLog OpLogStore - IDGenerator influxdb.IDGenerator + IDGenerator platform.IDGenerator TimeGenerator influxdb.TimeGenerator } @@ -61,7 +64,7 @@ func NewService(store kv.Store, opLog OpLogStore) *Service { } // FindDashboardByID retrieves a dashboard by id. -func (s *Service) FindDashboardByID(ctx context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { +func (s *Service) FindDashboardByID(ctx context.Context, id platform.ID) (*influxdb.Dashboard, error) { var d *influxdb.Dashboard err := s.kv.View(ctx, func(tx kv.Tx) error { @@ -74,7 +77,7 @@ func (s *Service) FindDashboardByID(ctx context.Context, id influxdb.ID) (*influ }) if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -82,10 +85,10 @@ func (s *Service) FindDashboardByID(ctx context.Context, id influxdb.ID) (*influ return d, nil } -func (s *Service) findDashboardByID(ctx context.Context, tx kv.Tx, id influxdb.ID) (*influxdb.Dashboard, error) { +func (s *Service) findDashboardByID(ctx context.Context, tx kv.Tx, id platform.ID) (*influxdb.Dashboard, error) { encodedID, err := id.Encode() if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -97,8 +100,8 @@ func (s *Service) findDashboardByID(ctx context.Context, tx kv.Tx, id influxdb.I v, err := b.Get(encodedID) if kv.IsNotFound(err) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrDashboardNotFound, } } @@ -109,7 +112,7 @@ func (s *Service) findDashboardByID(ctx context.Context, tx kv.Tx, id influxdb.I var d influxdb.Dashboard if err := json.Unmarshal(v, &d); err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -140,8 +143,8 @@ func (s *Service) FindDashboard(ctx context.Context, filter influxdb.DashboardFi } if d == nil { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrDashboardNotFound, } } @@ -172,8 +175,8 @@ func (s *Service) FindDashboards(ctx context.Context, filter influxdb.DashboardF ds := []*influxdb.Dashboard{} if len(filter.IDs) == 1 { d, err := s.FindDashboardByID(ctx, *filter.IDs[0]) - if err != nil && influxdb.ErrorCode(err) != influxdb.ENotFound { - return ds, 0, &influxdb.Error{ + if err != nil && errors.ErrorCode(err) != errors.ENotFound { + return ds, 0, &errors.Error{ Err: err, } } @@ -184,7 +187,7 @@ func (s *Service) FindDashboards(ctx context.Context, filter influxdb.DashboardF } err := s.kv.View(ctx, func(tx kv.Tx) error { dashs, err := s.findDashboards(ctx, tx, filter, opts) - if err != nil && influxdb.ErrorCode(err) != influxdb.ENotFound { + if err != nil && errors.ErrorCode(err) != errors.ENotFound { return err } ds = dashs @@ -192,7 +195,7 @@ func (s *Service) FindDashboards(ctx context.Context, filter influxdb.DashboardF }) if err != nil { - return nil, 0, &influxdb.Error{ + return nil, 0, &errors.Error{ Err: err, } } @@ -202,7 +205,7 @@ func (s *Service) FindDashboards(ctx context.Context, filter influxdb.DashboardF return ds, len(ds), nil } -func (s *Service) findOrganizationDashboards(ctx context.Context, tx kv.Tx, orgID influxdb.ID, filter influxdb.DashboardFilter) ([]*influxdb.Dashboard, error) { +func (s *Service) findOrganizationDashboards(ctx context.Context, tx kv.Tx, orgID platform.ID, filter influxdb.DashboardFilter) ([]*influxdb.Dashboard, error) { idx, err := tx.Bucket(orgDashboardIndex) if err != nil { return nil, err @@ -240,17 +243,17 @@ func (s *Service) findOrganizationDashboards(ctx context.Context, tx kv.Tx, orgI return ds, nil } -func decodeOrgDashboardIndexKey(indexKey []byte) (orgID influxdb.ID, dashID influxdb.ID, err error) { - if len(indexKey) != 2*influxdb.IDLength { - return 0, 0, &influxdb.Error{Code: influxdb.EInternal, Msg: "malformed org dashboard index key (please report this error)"} +func decodeOrgDashboardIndexKey(indexKey []byte) (orgID platform.ID, dashID platform.ID, err error) { + if len(indexKey) != 2*platform.IDLength { + return 0, 0, &errors.Error{Code: errors.EInternal, Msg: "malformed org dashboard index key (please report this error)"} } - if err := (&orgID).Decode(indexKey[:influxdb.IDLength]); err != nil { - return 0, 0, &influxdb.Error{Code: influxdb.EInternal, Msg: "bad org id", Err: influxdb.ErrInvalidID} + if err := (&orgID).Decode(indexKey[:platform.IDLength]); err != nil { + return 0, 0, &errors.Error{Code: errors.EInternal, Msg: "bad org id", Err: platform.ErrInvalidID} } - if err := (&dashID).Decode(indexKey[influxdb.IDLength:]); err != nil { - return 0, 0, &influxdb.Error{Code: influxdb.EInternal, Msg: "bad dashboard id", Err: influxdb.ErrInvalidID} + if err := (&dashID).Decode(indexKey[platform.IDLength:]); err != nil { + return 0, 0, &errors.Error{Code: errors.EInternal, Msg: "bad dashboard id", Err: platform.ErrInvalidID} } return orgID, dashID, nil @@ -276,7 +279,7 @@ func (s *Service) findDashboards(ctx context.Context, tx kv.Tx, filter influxdb. if filter.OrganizationID != nil { orgDashboards, err := s.findOrganizationDashboards(ctx, tx, *filter.OrganizationID, filter) if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -349,14 +352,14 @@ func (s *Service) CreateDashboard(ctx context.Context, d *influxdb.Dashboard) er return nil }) if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } return nil } -func (s *Service) createCellView(ctx context.Context, tx kv.Tx, dashID, cellID influxdb.ID, view *influxdb.View) error { +func (s *Service) createCellView(ctx context.Context, tx kv.Tx, dashID, cellID platform.ID, view *influxdb.View) error { if view == nil { // If not view exists create the view view = &influxdb.View{} @@ -367,7 +370,7 @@ func (s *Service) createCellView(ctx context.Context, tx kv.Tx, dashID, cellID i } // ReplaceDashboardCells updates the positions of each cell in a dashboard concurrently. -func (s *Service) ReplaceDashboardCells(ctx context.Context, id influxdb.ID, cs []*influxdb.Cell) error { +func (s *Service) ReplaceDashboardCells(ctx context.Context, id platform.ID, cs []*influxdb.Cell) error { err := s.kv.Update(ctx, func(tx kv.Tx) error { d, err := s.findDashboardByID(ctx, tx, id) if err != nil { @@ -381,15 +384,15 @@ func (s *Service) ReplaceDashboardCells(ctx context.Context, id influxdb.ID, cs for _, cell := range cs { if !cell.ID.Valid() { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "cannot provide empty cell id", } } if _, ok := ids[cell.ID.String()]; !ok { - return &influxdb.Error{ - Code: influxdb.EConflict, + return &errors.Error{ + Code: errors.EConflict, Msg: "cannot replace cells that were not already present", } } @@ -403,14 +406,14 @@ func (s *Service) ReplaceDashboardCells(ctx context.Context, id influxdb.ID, cs return s.putDashboardWithMeta(ctx, tx, d) }) if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } return nil } -func (s *Service) addDashboardCell(ctx context.Context, tx kv.Tx, id influxdb.ID, cell *influxdb.Cell, opts influxdb.AddDashboardCellOptions) error { +func (s *Service) addDashboardCell(ctx context.Context, tx kv.Tx, id platform.ID, cell *influxdb.Cell, opts influxdb.AddDashboardCellOptions) error { d, err := s.findDashboardByID(ctx, tx, id) if err != nil { return err @@ -430,12 +433,12 @@ func (s *Service) addDashboardCell(ctx context.Context, tx kv.Tx, id influxdb.ID } // AddDashboardCell adds a cell to a dashboard and sets the cells ID. -func (s *Service) AddDashboardCell(ctx context.Context, id influxdb.ID, cell *influxdb.Cell, opts influxdb.AddDashboardCellOptions) error { +func (s *Service) AddDashboardCell(ctx context.Context, id platform.ID, cell *influxdb.Cell, opts influxdb.AddDashboardCellOptions) error { err := s.kv.Update(ctx, func(tx kv.Tx) error { return s.addDashboardCell(ctx, tx, id, cell, opts) }) if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -443,11 +446,11 @@ func (s *Service) AddDashboardCell(ctx context.Context, id influxdb.ID, cell *in } // RemoveDashboardCell removes a cell from a dashboard. -func (s *Service) RemoveDashboardCell(ctx context.Context, dashboardID, cellID influxdb.ID) error { +func (s *Service) RemoveDashboardCell(ctx context.Context, dashboardID, cellID platform.ID) error { return s.kv.Update(ctx, func(tx kv.Tx) error { d, err := s.findDashboardByID(ctx, tx, dashboardID) if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -460,14 +463,14 @@ func (s *Service) RemoveDashboardCell(ctx context.Context, dashboardID, cellID i } } if idx == -1 { - return &influxdb.Error{ - Code: influxdb.ENotFound, + return &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrCellNotFound, } } if err := s.deleteDashboardCellView(ctx, tx, d.ID, d.Cells[idx].ID); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -475,13 +478,13 @@ func (s *Service) RemoveDashboardCell(ctx context.Context, dashboardID, cellID i d.Cells = append(d.Cells[:idx], d.Cells[idx+1:]...) if err := s.appendDashboardEventToLog(ctx, tx, d.ID, dashboardCellRemovedEvent); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } if err := s.putDashboardWithMeta(ctx, tx, d); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -490,7 +493,7 @@ func (s *Service) RemoveDashboardCell(ctx context.Context, dashboardID, cellID i } // GetDashboardCellView retrieves the view for a dashboard cell. -func (s *Service) GetDashboardCellView(ctx context.Context, dashboardID, cellID influxdb.ID) (*influxdb.View, error) { +func (s *Service) GetDashboardCellView(ctx context.Context, dashboardID, cellID platform.ID) (*influxdb.View, error) { var v *influxdb.View err := s.kv.View(ctx, func(tx kv.Tx) error { view, err := s.findDashboardCellView(ctx, tx, dashboardID, cellID) @@ -503,7 +506,7 @@ func (s *Service) GetDashboardCellView(ctx context.Context, dashboardID, cellID }) if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -511,10 +514,10 @@ func (s *Service) GetDashboardCellView(ctx context.Context, dashboardID, cellID return v, nil } -func (s *Service) findDashboardCellView(ctx context.Context, tx kv.Tx, dashboardID, cellID influxdb.ID) (*influxdb.View, error) { +func (s *Service) findDashboardCellView(ctx context.Context, tx kv.Tx, dashboardID, cellID platform.ID) (*influxdb.View, error) { k, err := encodeDashboardCellViewID(dashboardID, cellID) if err != nil { - return nil, influxdb.NewError(influxdb.WithErrorErr(err)) + return nil, errors.NewError(errors.WithErrorErr(err)) } vb, err := tx.Bucket(dashboardCellViewBucket) @@ -524,7 +527,7 @@ func (s *Service) findDashboardCellView(ctx context.Context, tx kv.Tx, dashboard v, err := vb.Get(k) if kv.IsNotFound(err) { - return nil, influxdb.NewError(influxdb.WithErrorCode(influxdb.ENotFound), influxdb.WithErrorMsg(influxdb.ErrViewNotFound)) + return nil, errors.NewError(errors.WithErrorCode(errors.ENotFound), errors.WithErrorMsg(influxdb.ErrViewNotFound)) } if err != nil { @@ -533,16 +536,16 @@ func (s *Service) findDashboardCellView(ctx context.Context, tx kv.Tx, dashboard view := &influxdb.View{} if err := json.Unmarshal(v, view); err != nil { - return nil, influxdb.NewError(influxdb.WithErrorErr(err)) + return nil, errors.NewError(errors.WithErrorErr(err)) } return view, nil } -func (s *Service) deleteDashboardCellView(ctx context.Context, tx kv.Tx, dashboardID, cellID influxdb.ID) error { +func (s *Service) deleteDashboardCellView(ctx context.Context, tx kv.Tx, dashboardID, cellID platform.ID) error { k, err := encodeDashboardCellViewID(dashboardID, cellID) if err != nil { - return influxdb.NewError(influxdb.WithErrorErr(err)) + return errors.NewError(errors.WithErrorErr(err)) } vb, err := tx.Bucket(dashboardCellViewBucket) @@ -551,21 +554,21 @@ func (s *Service) deleteDashboardCellView(ctx context.Context, tx kv.Tx, dashboa } if err := vb.Delete(k); err != nil { - return influxdb.NewError(influxdb.WithErrorErr(err)) + return errors.NewError(errors.WithErrorErr(err)) } return nil } -func (s *Service) putDashboardCellView(ctx context.Context, tx kv.Tx, dashboardID, cellID influxdb.ID, view *influxdb.View) error { +func (s *Service) putDashboardCellView(ctx context.Context, tx kv.Tx, dashboardID, cellID platform.ID, view *influxdb.View) error { k, err := encodeDashboardCellViewID(dashboardID, cellID) if err != nil { - return influxdb.NewError(influxdb.WithErrorErr(err)) + return errors.NewError(errors.WithErrorErr(err)) } v, err := json.Marshal(view) if err != nil { - return influxdb.NewError(influxdb.WithErrorErr(err)) + return errors.NewError(errors.WithErrorErr(err)) } vb, err := tx.Bucket(dashboardCellViewBucket) @@ -574,13 +577,13 @@ func (s *Service) putDashboardCellView(ctx context.Context, tx kv.Tx, dashboardI } if err := vb.Put(k, v); err != nil { - return influxdb.NewError(influxdb.WithErrorErr(err)) + return errors.NewError(errors.WithErrorErr(err)) } return nil } -func encodeDashboardCellViewID(dashID, cellID influxdb.ID) ([]byte, error) { +func encodeDashboardCellViewID(dashID, cellID platform.ID) ([]byte, error) { did, err := dashID.Encode() if err != nil { return nil, err @@ -604,7 +607,7 @@ func encodeDashboardCellViewID(dashID, cellID influxdb.ID) ([]byte, error) { } // UpdateDashboardCellView updates the view for a dashboard cell. -func (s *Service) UpdateDashboardCellView(ctx context.Context, dashboardID, cellID influxdb.ID, upd influxdb.ViewUpdate) (*influxdb.View, error) { +func (s *Service) UpdateDashboardCellView(ctx context.Context, dashboardID, cellID platform.ID, upd influxdb.ViewUpdate) (*influxdb.View, error) { var v *influxdb.View err := s.kv.Update(ctx, func(tx kv.Tx) error { @@ -626,7 +629,7 @@ func (s *Service) UpdateDashboardCellView(ctx context.Context, dashboardID, cell }) if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -635,9 +638,9 @@ func (s *Service) UpdateDashboardCellView(ctx context.Context, dashboardID, cell } // UpdateDashboardCell udpates a cell on a dashboard. -func (s *Service) UpdateDashboardCell(ctx context.Context, dashboardID, cellID influxdb.ID, upd influxdb.CellUpdate) (*influxdb.Cell, error) { +func (s *Service) UpdateDashboardCell(ctx context.Context, dashboardID, cellID platform.ID, upd influxdb.CellUpdate) (*influxdb.Cell, error) { if err := upd.Valid(); err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -657,8 +660,8 @@ func (s *Service) UpdateDashboardCell(ctx context.Context, dashboardID, cellID i } } if idx == -1 { - return &influxdb.Error{ - Code: influxdb.ENotFound, + return &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrCellNotFound, } } @@ -677,7 +680,7 @@ func (s *Service) UpdateDashboardCell(ctx context.Context, dashboardID, cellID i }) if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -702,7 +705,7 @@ func (s *Service) PutDashboard(ctx context.Context, d *influxdb.Dashboard) error }) } -func encodeOrgDashboardIndex(orgID influxdb.ID, dashID influxdb.ID) ([]byte, error) { +func encodeOrgDashboardIndex(orgID platform.ID, dashID platform.ID) ([]byte, error) { oid, err := orgID.Encode() if err != nil { return nil, err @@ -817,7 +820,7 @@ func (s *Service) forEachDashboard(ctx context.Context, tx kv.Tx, descending boo } // UpdateDashboard updates a dashboard according the parameters set on upd. -func (s *Service) UpdateDashboard(ctx context.Context, id influxdb.ID, upd influxdb.DashboardUpdate) (*influxdb.Dashboard, error) { +func (s *Service) UpdateDashboard(ctx context.Context, id platform.ID, upd influxdb.DashboardUpdate) (*influxdb.Dashboard, error) { if err := upd.Valid(); err != nil { return nil, err } @@ -833,7 +836,7 @@ func (s *Service) UpdateDashboard(ctx context.Context, id influxdb.ID, upd influ return nil }) if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -841,7 +844,7 @@ func (s *Service) UpdateDashboard(ctx context.Context, id influxdb.ID, upd influ return d, err } -func (s *Service) updateDashboard(ctx context.Context, tx kv.Tx, id influxdb.ID, upd influxdb.DashboardUpdate) (*influxdb.Dashboard, error) { +func (s *Service) updateDashboard(ctx context.Context, tx kv.Tx, id platform.ID, upd influxdb.DashboardUpdate) (*influxdb.Dashboard, error) { d, err := s.findDashboardByID(ctx, tx, id) if err != nil { return nil, err @@ -887,10 +890,10 @@ func (s *Service) updateDashboard(ctx context.Context, tx kv.Tx, id influxdb.ID, } // DeleteDashboard deletes a dashboard and prunes it from the index. -func (s *Service) DeleteDashboard(ctx context.Context, id influxdb.ID) error { +func (s *Service) DeleteDashboard(ctx context.Context, id platform.ID) error { return s.kv.Update(ctx, func(tx kv.Tx) error { if pe := s.deleteDashboard(ctx, tx, id); pe != nil { - return &influxdb.Error{ + return &errors.Error{ Err: pe, } } @@ -898,7 +901,7 @@ func (s *Service) DeleteDashboard(ctx context.Context, id influxdb.ID) error { }) } -func (s *Service) deleteDashboard(ctx context.Context, tx kv.Tx, id influxdb.ID) error { +func (s *Service) deleteDashboard(ctx context.Context, tx kv.Tx, id platform.ID) error { d, err := s.findDashboardByID(ctx, tx, id) if err != nil { return err @@ -906,7 +909,7 @@ func (s *Service) deleteDashboard(ctx context.Context, tx kv.Tx, id influxdb.ID) for _, cell := range d.Cells { if err := s.deleteDashboardCellView(ctx, tx, d.ID, cell.ID); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -914,13 +917,13 @@ func (s *Service) deleteDashboard(ctx context.Context, tx kv.Tx, id influxdb.ID) encodedID, err := id.Encode() if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } if err := s.removeOrganizationDashboardIndex(ctx, tx, d); err != nil { - return influxdb.NewError(influxdb.WithErrorErr(err)) + return errors.NewError(errors.WithErrorErr(err)) } b, err := tx.Bucket(dashboardBucket) @@ -929,13 +932,13 @@ func (s *Service) deleteDashboard(ctx context.Context, tx kv.Tx, id influxdb.ID) } if err := b.Delete(encodedID); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } if err := s.appendDashboardEventToLog(ctx, tx, d.ID, dashboardRemovedEvent); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -945,7 +948,7 @@ func (s *Service) deleteDashboard(ctx context.Context, tx kv.Tx, id influxdb.ID) const dashboardOperationLogKeyPrefix = "dashboard" -func encodeDashboardOperationLogKey(id influxdb.ID) ([]byte, error) { +func encodeDashboardOperationLogKey(id platform.ID) ([]byte, error) { buf, err := id.Encode() if err != nil { return nil, err @@ -954,7 +957,7 @@ func encodeDashboardOperationLogKey(id influxdb.ID) ([]byte, error) { } // GetDashboardOperationLog retrieves a dashboards operation log. -func (s *Service) GetDashboardOperationLog(ctx context.Context, id influxdb.ID, opts influxdb.FindOptions) ([]*influxdb.OperationLogEntry, int, error) { +func (s *Service) GetDashboardOperationLog(ctx context.Context, id platform.ID, opts influxdb.FindOptions) ([]*influxdb.OperationLogEntry, int, error) { // TODO(desa): might be worthwhile to allocate a slice of size opts.Limit log := []*influxdb.OperationLogEntry{} @@ -984,7 +987,7 @@ func (s *Service) GetDashboardOperationLog(ctx context.Context, id influxdb.ID, return log, len(log), nil } -func (s *Service) appendDashboardEventToLog(ctx context.Context, tx kv.Tx, id influxdb.ID, st string) error { +func (s *Service) appendDashboardEventToLog(ctx context.Context, tx kv.Tx, id platform.ID, st string) error { e := &influxdb.OperationLogEntry{ Description: st, } diff --git a/dashboards/testing/dashboards.go b/dashboards/testing/dashboards.go index 58f992b7875..cb308f575d8 100644 --- a/dashboards/testing/dashboards.go +++ b/dashboards/testing/dashboards.go @@ -6,6 +6,9 @@ import ( "testing" "time" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" platform "github.com/influxdata/influxdb/v2" @@ -36,7 +39,7 @@ var dashboardCmpOptions = cmp.Options{ // DashboardFields will include the IDGenerator, and dashboards type DashboardFields struct { - IDGenerator platform.IDGenerator + IDGenerator platform2.IDGenerator TimeGenerator platform.TimeGenerator Dashboards []*platform.Dashboard Views []*platform.View @@ -128,7 +131,7 @@ func CreateDashboard( name: "basic create dashboard", fields: DashboardFields{ IDGenerator: &mock.IDGenerator{ - IDFn: func() platform.ID { + IDFn: func() platform2.ID { return MustIDBase16(dashTwoID) }, }, @@ -173,7 +176,7 @@ func CreateDashboard( name: "create dashboard with missing id", fields: DashboardFields{ IDGenerator: &mock.IDGenerator{ - IDFn: func() platform.ID { + IDFn: func() platform2.ID { return MustIDBase16(dashTwoID) }, }, @@ -240,7 +243,7 @@ func AddDashboardCell( t *testing.T, ) { type args struct { - dashboardID platform.ID + dashboardID platform2.ID cell *platform.Cell } type wants struct { @@ -258,7 +261,7 @@ func AddDashboardCell( name: "basic add cell", fields: DashboardFields{ IDGenerator: &mock.IDGenerator{ - IDFn: func() platform.ID { + IDFn: func() platform2.ID { return MustIDBase16(dashTwoID) }, }, @@ -307,7 +310,7 @@ func AddDashboardCell( fields: DashboardFields{ TimeGenerator: mock.TimeGenerator{FakeValue: time.Date(2009, time.November, 10, 24, 0, 0, 0, time.UTC)}, IDGenerator: &mock.IDGenerator{ - IDFn: func() platform.ID { + IDFn: func() platform2.ID { return MustIDBase16(dashTwoID) }, }, @@ -353,7 +356,7 @@ func AddDashboardCell( fields: DashboardFields{ TimeGenerator: mock.TimeGenerator{FakeValue: time.Date(2009, time.November, 10, 24, 0, 0, 0, time.UTC)}, IDGenerator: &mock.IDGenerator{ - IDFn: func() platform.ID { + IDFn: func() platform2.ID { return MustIDBase16(dashTwoID) }, }, @@ -377,8 +380,8 @@ func AddDashboardCell( cell: &platform.Cell{}, }, wants: wants{ - err: &platform.Error{ - Code: platform.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: platform.OpAddDashboardCell, Msg: platform.ErrDashboardNotFound, }, @@ -420,7 +423,7 @@ func FindDashboardByID( t *testing.T, ) { type args struct { - id platform.ID + id platform2.ID } type wants struct { err error @@ -480,8 +483,8 @@ func FindDashboardByID( id: MustIDBase16(dashThreeID), }, wants: wants{ - err: &platform.Error{ - Code: platform.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: platform.OpFindDashboardByID, Msg: platform.ErrDashboardNotFound, }, @@ -511,9 +514,9 @@ func FindDashboards( t *testing.T, ) { type args struct { - IDs []*platform.ID - organizationID *platform.ID - ownerID *platform.ID + IDs []*platform2.ID + organizationID *platform2.ID + ownerID *platform2.ID findOptions platform.FindOptions } @@ -868,7 +871,7 @@ func FindDashboards( }, }, args: args{ - IDs: []*platform.ID{ + IDs: []*platform2.ID{ idPtr(MustIDBase16(dashTwoID)), }, findOptions: platform.DefaultDashboardFindOptions, @@ -900,7 +903,7 @@ func FindDashboards( }, }, args: args{ - IDs: []*platform.ID{ + IDs: []*platform2.ID{ idPtr(MustIDBase16(dashOneID)), idPtr(MustIDBase16(dashTwoID)), }, @@ -984,7 +987,7 @@ func FindDashboards( }, }, args: args{ - IDs: []*platform.ID{ + IDs: []*platform2.ID{ idPtr(MustIDBase16(dashThreeID)), }, findOptions: platform.DefaultDashboardFindOptions, @@ -1028,7 +1031,7 @@ func DeleteDashboard( t *testing.T, ) { type args struct { - ID platform.ID + ID platform2.ID } type wants struct { err error @@ -1090,8 +1093,8 @@ func DeleteDashboard( ID: MustIDBase16(dashThreeID), }, wants: wants{ - err: &platform.Error{ - Code: platform.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: platform.OpDeleteDashboard, Msg: platform.ErrDashboardNotFound, }, @@ -1139,7 +1142,7 @@ func UpdateDashboard( type args struct { name string description string - id platform.ID + id platform2.ID cells []*platform.Cell } type wants struct { @@ -1256,7 +1259,7 @@ func UpdateDashboard( name: "update description name and cells", fields: DashboardFields{ TimeGenerator: mock.TimeGenerator{FakeValue: time.Date(2009, time.November, 10, 24, 0, 0, 0, time.UTC)}, - IDGenerator: mock.IDGenerator{IDFn: func() platform.ID { + IDGenerator: mock.IDGenerator{IDFn: func() platform2.ID { return 5 }}, Dashboards: []*platform.Dashboard{ @@ -1338,8 +1341,8 @@ func UpdateDashboard( name: "changed", }, wants: wants{ - err: &platform.Error{ - Code: platform.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: platform.OpUpdateDashboard, Msg: platform.ErrDashboardNotFound, }, @@ -1380,8 +1383,8 @@ func RemoveDashboardCell( t *testing.T, ) { type args struct { - dashboardID platform.ID - cellID platform.ID + dashboardID platform2.ID + cellID platform2.ID } type wants struct { err error @@ -1399,7 +1402,7 @@ func RemoveDashboardCell( fields: DashboardFields{ TimeGenerator: mock.TimeGenerator{FakeValue: time.Date(2009, time.November, 10, 24, 0, 0, 0, time.UTC)}, IDGenerator: &mock.IDGenerator{ - IDFn: func() platform.ID { + IDFn: func() platform2.ID { return MustIDBase16(dashTwoID) }, }, @@ -1477,8 +1480,8 @@ func UpdateDashboardCell( t *testing.T, ) { type args struct { - dashboardID platform.ID - cellID platform.ID + dashboardID platform2.ID + cellID platform2.ID cellUpdate platform.CellUpdate } type wants struct { @@ -1497,7 +1500,7 @@ func UpdateDashboardCell( fields: DashboardFields{ TimeGenerator: mock.TimeGenerator{FakeValue: time.Date(2009, time.November, 10, 24, 0, 0, 0, time.UTC)}, IDGenerator: &mock.IDGenerator{ - IDFn: func() platform.ID { + IDFn: func() platform2.ID { return MustIDBase16(dashTwoID) }, }, @@ -1553,7 +1556,7 @@ func UpdateDashboardCell( fields: DashboardFields{ TimeGenerator: mock.TimeGenerator{FakeValue: time.Date(2009, time.November, 10, 24, 0, 0, 0, time.UTC)}, IDGenerator: &mock.IDGenerator{ - IDFn: func() platform.ID { + IDFn: func() platform2.ID { return MustIDBase16(dashTwoID) }, }, @@ -1594,8 +1597,8 @@ func UpdateDashboardCell( }, }, }, - err: &platform.Error{ - Code: platform.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Op: platform.OpUpdateDashboardCell, Msg: "must update at least one attribute", }, @@ -1606,7 +1609,7 @@ func UpdateDashboardCell( fields: DashboardFields{ TimeGenerator: mock.TimeGenerator{FakeValue: time.Date(2009, time.November, 10, 24, 0, 0, 0, time.UTC)}, IDGenerator: &mock.IDGenerator{ - IDFn: func() platform.ID { + IDFn: func() platform2.ID { return MustIDBase16(dashTwoID) }, }, @@ -1649,8 +1652,8 @@ func UpdateDashboardCell( }, }, }, - err: &platform.Error{ - Code: platform.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: platform.OpUpdateDashboardCell, Msg: platform.ErrCellNotFound, }, @@ -1685,7 +1688,7 @@ func ReplaceDashboardCells( t *testing.T, ) { type args struct { - dashboardID platform.ID + dashboardID platform2.ID cells []*platform.Cell } type wants struct { @@ -1704,7 +1707,7 @@ func ReplaceDashboardCells( fields: DashboardFields{ TimeGenerator: mock.TimeGenerator{FakeValue: time.Date(2009, time.November, 10, 24, 0, 0, 0, time.UTC)}, IDGenerator: &mock.IDGenerator{ - IDFn: func() platform.ID { + IDFn: func() platform2.ID { return MustIDBase16(dashTwoID) }, }, @@ -1785,7 +1788,7 @@ func ReplaceDashboardCells( fields: DashboardFields{ TimeGenerator: mock.TimeGenerator{FakeValue: time.Date(2009, time.November, 10, 24, 0, 0, 0, time.UTC)}, IDGenerator: &mock.IDGenerator{ - IDFn: func() platform.ID { + IDFn: func() platform2.ID { return MustIDBase16(dashTwoID) }, }, @@ -1827,8 +1830,8 @@ func ReplaceDashboardCells( }, }, wants: wants{ - err: &platform.Error{ - Code: platform.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Op: platform.OpReplaceDashboardCells, Msg: "cannot replace cells that were not already present", }, @@ -1875,8 +1878,8 @@ func GetDashboardCellView( t *testing.T, ) { type args struct { - dashboardID platform.ID - cellID platform.ID + dashboardID platform2.ID + cellID platform2.ID } type wants struct { err error @@ -1939,8 +1942,8 @@ func GetDashboardCellView( cellID: 5, }, wants: wants{ - err: &platform.Error{ - Code: platform.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: platform.OpGetDashboardCellView, Msg: platform.ErrViewNotFound, }, @@ -1970,8 +1973,8 @@ func UpdateDashboardCellView( t *testing.T, ) { type args struct { - dashboardID platform.ID - cellID platform.ID + dashboardID platform2.ID + cellID platform2.ID properties platform.ViewProperties name string } @@ -2112,8 +2115,8 @@ func UpdateDashboardCellView( cellID: 5, }, wants: wants{ - err: &platform.Error{ - Code: platform.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: platform.OpGetDashboardCellView, Msg: platform.ErrViewNotFound, }, diff --git a/dashboards/testing/util.go b/dashboards/testing/util.go index ea0cb3e9714..2de0a5d9ee5 100644 --- a/dashboards/testing/util.go +++ b/dashboards/testing/util.go @@ -4,6 +4,9 @@ import ( "context" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) @@ -28,14 +31,14 @@ func ErrorsEqual(t *testing.T, actual, expected error) { t.Errorf("expected error %s but received nil", expected.Error()) } - if influxdb.ErrorCode(expected) != influxdb.ErrorCode(actual) { + if errors.ErrorCode(expected) != errors.ErrorCode(actual) { t.Logf("\nexpected: %v\nactual: %v\n\n", expected, actual) - t.Errorf("expected error code %q but received %q", influxdb.ErrorCode(expected), influxdb.ErrorCode(actual)) + t.Errorf("expected error code %q but received %q", errors.ErrorCode(expected), errors.ErrorCode(actual)) } - if influxdb.ErrorMessage(expected) != influxdb.ErrorMessage(actual) { + if errors.ErrorMessage(expected) != errors.ErrorMessage(actual) { t.Logf("\nexpected: %v\nactual: %v\n\n", expected, actual) - t.Errorf("expected error message %q but received %q", influxdb.ErrorMessage(expected), influxdb.ErrorMessage(actual)) + t.Errorf("expected error message %q but received %q", errors.ErrorMessage(expected), errors.ErrorMessage(actual)) } } @@ -46,13 +49,13 @@ func FloatPtr(f float64) *float64 { return p } -func idPtr(id influxdb.ID) *influxdb.ID { +func idPtr(id platform.ID) *platform.ID { return &id } // MustIDBase16 is an helper to ensure a correct ID is built during testing. -func MustIDBase16(s string) influxdb.ID { - id, err := influxdb.IDFromString(s) +func MustIDBase16(s string) platform.ID { + id, err := platform.IDFromString(s) if err != nil { panic(err) } @@ -60,7 +63,7 @@ func MustIDBase16(s string) influxdb.ID { } // MustIDBase16Ptr is an helper to ensure a correct ID ptr ref is built during testing. -func MustIDBase16Ptr(s string) *influxdb.ID { +func MustIDBase16Ptr(s string) *platform.ID { id := MustIDBase16(s) return &id } @@ -97,7 +100,7 @@ func MustCreateMappings(ctx context.Context, svc influxdb.UserResourceMappingSer } } -func MustMakeUsersOrgOwner(ctx context.Context, svc influxdb.UserResourceMappingService, oid influxdb.ID, uids ...influxdb.ID) { +func MustMakeUsersOrgOwner(ctx context.Context, svc influxdb.UserResourceMappingService, oid platform.ID, uids ...platform.ID) { ms := make([]*influxdb.UserResourceMapping, len(uids)) for i, uid := range uids { ms[i] = &influxdb.UserResourceMapping{ @@ -110,7 +113,7 @@ func MustMakeUsersOrgOwner(ctx context.Context, svc influxdb.UserResourceMapping MustCreateMappings(ctx, svc, ms...) } -func MustMakeUsersOrgMember(ctx context.Context, svc influxdb.UserResourceMappingService, oid influxdb.ID, uids ...influxdb.ID) { +func MustMakeUsersOrgMember(ctx context.Context, svc influxdb.UserResourceMappingService, oid platform.ID, uids ...platform.ID) { ms := make([]*influxdb.UserResourceMapping, len(uids)) for i, uid := range uids { ms[i] = &influxdb.UserResourceMapping{ @@ -123,7 +126,7 @@ func MustMakeUsersOrgMember(ctx context.Context, svc influxdb.UserResourceMappin MustCreateMappings(ctx, svc, ms...) } -func MustNewPermissionAtID(id influxdb.ID, a influxdb.Action, rt influxdb.ResourceType, orgID influxdb.ID) *influxdb.Permission { +func MustNewPermissionAtID(id platform.ID, a influxdb.Action, rt influxdb.ResourceType, orgID platform.ID) *influxdb.Permission { perm, err := influxdb.NewPermissionAtID(id, a, rt, orgID) if err != nil { panic(err) diff --git a/dashboards/transport/http.go b/dashboards/transport/http.go index a197512d4a8..faf4e1d40e4 100644 --- a/dashboards/transport/http.go +++ b/dashboards/transport/http.go @@ -7,6 +7,9 @@ import ( "net/http" "path" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/influxdata/influxdb/v2" @@ -112,8 +115,8 @@ type dashboardLinks struct { } type dashboardResponse struct { - ID influxdb.ID `json:"id,omitempty"` - OrganizationID influxdb.ID `json:"orgID,omitempty"` + ID platform.ID `json:"id,omitempty"` + OrganizationID platform.ID `json:"orgID,omitempty"` Name string `json:"name"` Description string `json:"description"` Meta influxdb.DashboardMeta `json:"meta"` @@ -204,7 +207,7 @@ func (c dashboardCellResponse) toinfluxdb() *influxdb.Cell { return &c.Cell } -func newDashboardCellResponse(dashboardID influxdb.ID, c *influxdb.Cell) dashboardCellResponse { +func newDashboardCellResponse(dashboardID platform.ID, c *influxdb.Cell) dashboardCellResponse { resp := dashboardCellResponse{ Cell: *c, Links: map[string]string{ @@ -225,7 +228,7 @@ type dashboardCellsResponse struct { Links map[string]string `json:"links"` } -func newDashboardCellsResponse(dashboardID influxdb.ID, cs []*influxdb.Cell) dashboardCellsResponse { +func newDashboardCellsResponse(dashboardID platform.ID, cs []*influxdb.Cell) dashboardCellsResponse { res := dashboardCellsResponse{ Cells: []dashboardCellResponse{}, Links: map[string]string{ @@ -266,7 +269,7 @@ func (r dashboardCellViewResponse) MarshalJSON() ([]byte, error) { }) } -func newDashboardCellViewResponse(dashID, cellID influxdb.ID, v *influxdb.View) dashboardCellViewResponse { +func newDashboardCellViewResponse(dashID, cellID platform.ID, v *influxdb.View) dashboardCellViewResponse { return dashboardCellViewResponse{ Links: viewLinks{ Self: fmt.Sprintf("/api/v2/dashboards/%s/cells/%s", dashID, cellID), @@ -322,7 +325,7 @@ func decodeGetDashboardsRequest(ctx context.Context, r *http.Request) (*getDashb } req.opts = *opts - initialID := influxdb.InvalidID() + initialID := platform.InvalidID() if ids, ok := qp["id"]; ok { for _, id := range ids { i := initialID @@ -337,7 +340,7 @@ func decodeGetDashboardsRequest(ctx context.Context, r *http.Request) (*getDashb return nil, err } } else if orgID := qp.Get("orgID"); orgID != "" { - id := influxdb.InvalidID() + id := platform.InvalidID() if err := id.DecodeFromString(orgID); err != nil { return nil, err } @@ -439,19 +442,19 @@ func (h *DashboardHandler) handleGetDashboard(w http.ResponseWriter, r *http.Req } type getDashboardRequest struct { - DashboardID influxdb.ID + DashboardID platform.ID } func decodeGetDashboardRequest(ctx context.Context, r *http.Request) (*getDashboardRequest, error) { id := chi.URLParam(r, "id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -481,19 +484,19 @@ func (h *DashboardHandler) handleDeleteDashboard(w http.ResponseWriter, r *http. } type deleteDashboardRequest struct { - DashboardID influxdb.ID + DashboardID platform.ID } func decodeDeleteDashboardRequest(ctx context.Context, r *http.Request) (*deleteDashboardRequest, error) { id := chi.URLParam(r, "id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -529,7 +532,7 @@ func (h *DashboardHandler) handlePatchDashboard(w http.ResponseWriter, r *http.R } type patchDashboardRequest struct { - DashboardID influxdb.ID + DashboardID platform.ID Upd influxdb.DashboardUpdate } @@ -537,8 +540,8 @@ func decodePatchDashboardRequest(ctx context.Context, r *http.Request) (*patchDa req := &patchDashboardRequest{} upd := influxdb.DashboardUpdate{} if err := json.NewDecoder(r.Body).Decode(&upd); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -546,12 +549,12 @@ func decodePatchDashboardRequest(ctx context.Context, r *http.Request) (*patchDa id := chi.URLParam(r, "id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -559,8 +562,8 @@ func decodePatchDashboardRequest(ctx context.Context, r *http.Request) (*patchDa req.DashboardID = i if err := req.Valid(); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -571,8 +574,8 @@ func decodePatchDashboardRequest(ctx context.Context, r *http.Request) (*patchDa // Valid validates that the dashboard ID is non zero valued and update has expected values set. func (r *patchDashboardRequest) Valid() error { if !r.DashboardID.Valid() { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "missing dashboard ID", } } @@ -584,9 +587,9 @@ func (r *patchDashboardRequest) Valid() error { } type postDashboardCellRequest struct { - dashboardID influxdb.ID + dashboardID platform.ID *influxdb.CellProperty - UsingView *influxdb.ID `json:"usingView"` + UsingView *platform.ID `json:"usingView"` Name *string `json:"name"` } @@ -594,15 +597,15 @@ func decodePostDashboardCellRequest(ctx context.Context, r *http.Request) (*post req := &postDashboardCellRequest{} id := chi.URLParam(r, "id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } if err := json.NewDecoder(r.Body).Decode(req); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "bad request json body", Err: err, } @@ -640,8 +643,8 @@ func (h *DashboardHandler) handlePostDashboardCell(w http.ResponseWriter, r *htt opts.View.Name = *req.Name } } else if req.CellProperty == nil { - h.api.Err(w, r, &influxdb.Error{ - Code: influxdb.EInvalid, + h.api.Err(w, r, &errors.Error{ + Code: errors.EInvalid, Msg: "req body is empty", }) return @@ -662,7 +665,7 @@ func (h *DashboardHandler) handlePostDashboardCell(w http.ResponseWriter, r *htt } type putDashboardCellRequest struct { - dashboardID influxdb.ID + dashboardID platform.ID cells []*influxdb.Cell } @@ -671,8 +674,8 @@ func decodePutDashboardCellRequest(ctx context.Context, r *http.Request) (*putDa id := chi.URLParam(r, "id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } @@ -708,8 +711,8 @@ func (h *DashboardHandler) handlePutDashboardCells(w http.ResponseWriter, r *htt } type deleteDashboardCellRequest struct { - dashboardID influxdb.ID - cellID influxdb.ID + dashboardID platform.ID + cellID platform.ID } func decodeDeleteDashboardCellRequest(ctx context.Context, r *http.Request) (*deleteDashboardCellRequest, error) { @@ -717,8 +720,8 @@ func decodeDeleteDashboardCellRequest(ctx context.Context, r *http.Request) (*de id := chi.URLParam(r, "id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } @@ -728,8 +731,8 @@ func decodeDeleteDashboardCellRequest(ctx context.Context, r *http.Request) (*de cellID := chi.URLParam(r, "cellID") if cellID == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing cellID", } } @@ -741,8 +744,8 @@ func decodeDeleteDashboardCellRequest(ctx context.Context, r *http.Request) (*de } type getDashboardCellViewRequest struct { - dashboardID influxdb.ID - cellID influxdb.ID + dashboardID platform.ID + cellID platform.ID } func decodeGetDashboardCellViewRequest(ctx context.Context, r *http.Request) (*getDashboardCellViewRequest, error) { @@ -750,7 +753,7 @@ func decodeGetDashboardCellViewRequest(ctx context.Context, r *http.Request) (*g id := chi.URLParam(r, "id") if id == "" { - return nil, influxdb.NewError(influxdb.WithErrorMsg("url missing id"), influxdb.WithErrorCode(influxdb.EInvalid)) + return nil, errors.NewError(errors.WithErrorMsg("url missing id"), errors.WithErrorCode(errors.EInvalid)) } if err := req.dashboardID.DecodeFromString(id); err != nil { return nil, err @@ -758,7 +761,7 @@ func decodeGetDashboardCellViewRequest(ctx context.Context, r *http.Request) (*g cellID := chi.URLParam(r, "cellID") if cellID == "" { - return nil, influxdb.NewError(influxdb.WithErrorMsg("url missing cellID"), influxdb.WithErrorCode(influxdb.EInvalid)) + return nil, errors.NewError(errors.WithErrorMsg("url missing cellID"), errors.WithErrorCode(errors.EInvalid)) } if err := req.cellID.DecodeFromString(cellID); err != nil { return nil, err @@ -787,8 +790,8 @@ func (h *DashboardHandler) handleGetDashboardCellView(w http.ResponseWriter, r * } type patchDashboardCellViewRequest struct { - dashboardID influxdb.ID - cellID influxdb.ID + dashboardID platform.ID + cellID platform.ID upd influxdb.ViewUpdate } @@ -797,7 +800,7 @@ func decodePatchDashboardCellViewRequest(ctx context.Context, r *http.Request) ( id := chi.URLParam(r, "id") if id == "" { - return nil, influxdb.NewError(influxdb.WithErrorMsg("url missing id"), influxdb.WithErrorCode(influxdb.EInvalid)) + return nil, errors.NewError(errors.WithErrorMsg("url missing id"), errors.WithErrorCode(errors.EInvalid)) } if err := req.dashboardID.DecodeFromString(id); err != nil { return nil, err @@ -805,7 +808,7 @@ func decodePatchDashboardCellViewRequest(ctx context.Context, r *http.Request) ( cellID := chi.URLParam(r, "cellID") if cellID == "" { - return nil, influxdb.NewError(influxdb.WithErrorMsg("url missing cellID"), influxdb.WithErrorCode(influxdb.EInvalid)) + return nil, errors.NewError(errors.WithErrorMsg("url missing cellID"), errors.WithErrorCode(errors.EInvalid)) } if err := req.cellID.DecodeFromString(cellID); err != nil { return nil, err @@ -854,8 +857,8 @@ func (h *DashboardHandler) handleDeleteDashboardCell(w http.ResponseWriter, r *h } type patchDashboardCellRequest struct { - dashboardID influxdb.ID - cellID influxdb.ID + dashboardID platform.ID + cellID platform.ID upd influxdb.CellUpdate } @@ -864,8 +867,8 @@ func decodePatchDashboardCellRequest(ctx context.Context, r *http.Request) (*pat id := chi.URLParam(r, "id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } @@ -875,8 +878,8 @@ func decodePatchDashboardCellRequest(ctx context.Context, r *http.Request) (*pat cellID := chi.URLParam(r, "cellID") if cellID == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "cannot provide empty cell id", } } @@ -885,8 +888,8 @@ func decodePatchDashboardCellRequest(ctx context.Context, r *http.Request) (*pat } if err := json.NewDecoder(r.Body).Decode(&req.upd); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -917,7 +920,7 @@ func (h *DashboardHandler) handlePatchDashboardCell(w http.ResponseWriter, r *ht h.api.Respond(w, r, http.StatusOK, newDashboardCellResponse(req.dashboardID, cell)) } -func (h *DashboardHandler) lookupOrgByDashboardID(ctx context.Context, id influxdb.ID) (influxdb.ID, error) { +func (h *DashboardHandler) lookupOrgByDashboardID(ctx context.Context, id platform.ID) (platform.ID, error) { d, err := h.dashboardService.FindDashboardByID(ctx, id) if err != nil { return 0, err @@ -931,7 +934,7 @@ type DashboardService struct { } // FindDashboardByID returns a single dashboard by ID. -func (s *DashboardService) FindDashboardByID(ctx context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { +func (s *DashboardService) FindDashboardByID(ctx context.Context, id platform.ID) (*influxdb.Dashboard, error) { var dr dashboardResponse err := s.Client. Get(prefixDashboards, id.String()). @@ -982,7 +985,7 @@ func (s *DashboardService) CreateDashboard(ctx context.Context, d *influxdb.Dash // UpdateDashboard updates a single dashboard with changeset. // Returns the new dashboard state after update. -func (s *DashboardService) UpdateDashboard(ctx context.Context, id influxdb.ID, upd influxdb.DashboardUpdate) (*influxdb.Dashboard, error) { +func (s *DashboardService) UpdateDashboard(ctx context.Context, id platform.ID, upd influxdb.DashboardUpdate) (*influxdb.Dashboard, error) { var d influxdb.Dashboard err := s.Client. PatchJSON(upd, prefixDashboards, id.String()). @@ -1001,14 +1004,14 @@ func (s *DashboardService) UpdateDashboard(ctx context.Context, id influxdb.ID, } // DeleteDashboard removes a dashboard by ID. -func (s *DashboardService) DeleteDashboard(ctx context.Context, id influxdb.ID) error { +func (s *DashboardService) DeleteDashboard(ctx context.Context, id platform.ID) error { return s.Client. Delete(dashboardIDPath(id)). Do(ctx) } // AddDashboardCell adds a cell to a dashboard. -func (s *DashboardService) AddDashboardCell(ctx context.Context, id influxdb.ID, c *influxdb.Cell, opts influxdb.AddDashboardCellOptions) error { +func (s *DashboardService) AddDashboardCell(ctx context.Context, id platform.ID, c *influxdb.Cell, opts influxdb.AddDashboardCellOptions) error { return s.Client. PostJSON(c, cellPath(id)). DecodeJSON(c). @@ -1016,16 +1019,16 @@ func (s *DashboardService) AddDashboardCell(ctx context.Context, id influxdb.ID, } // RemoveDashboardCell removes a dashboard. -func (s *DashboardService) RemoveDashboardCell(ctx context.Context, dashboardID, cellID influxdb.ID) error { +func (s *DashboardService) RemoveDashboardCell(ctx context.Context, dashboardID, cellID platform.ID) error { return s.Client. Delete(dashboardCellIDPath(dashboardID, cellID)). Do(ctx) } // UpdateDashboardCell replaces the dashboard cell with the provided ID. -func (s *DashboardService) UpdateDashboardCell(ctx context.Context, dashboardID, cellID influxdb.ID, upd influxdb.CellUpdate) (*influxdb.Cell, error) { +func (s *DashboardService) UpdateDashboardCell(ctx context.Context, dashboardID, cellID platform.ID, upd influxdb.CellUpdate) (*influxdb.Cell, error) { if err := upd.Valid(); err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -1043,7 +1046,7 @@ func (s *DashboardService) UpdateDashboardCell(ctx context.Context, dashboardID, } // GetDashboardCellView retrieves the view for a dashboard cell. -func (s *DashboardService) GetDashboardCellView(ctx context.Context, dashboardID, cellID influxdb.ID) (*influxdb.View, error) { +func (s *DashboardService) GetDashboardCellView(ctx context.Context, dashboardID, cellID platform.ID) (*influxdb.View, error) { var dcv dashboardCellViewResponse err := s.Client. Get(cellViewPath(dashboardID, cellID)). @@ -1057,7 +1060,7 @@ func (s *DashboardService) GetDashboardCellView(ctx context.Context, dashboardID } // UpdateDashboardCellView updates the view for a dashboard cell. -func (s *DashboardService) UpdateDashboardCellView(ctx context.Context, dashboardID, cellID influxdb.ID, upd influxdb.ViewUpdate) (*influxdb.View, error) { +func (s *DashboardService) UpdateDashboardCellView(ctx context.Context, dashboardID, cellID platform.ID, upd influxdb.ViewUpdate) (*influxdb.View, error) { var dcv dashboardCellViewResponse err := s.Client. PatchJSON(upd, cellViewPath(dashboardID, cellID)). @@ -1070,7 +1073,7 @@ func (s *DashboardService) UpdateDashboardCellView(ctx context.Context, dashboar } // ReplaceDashboardCells replaces all cells in a dashboard -func (s *DashboardService) ReplaceDashboardCells(ctx context.Context, id influxdb.ID, cs []*influxdb.Cell) error { +func (s *DashboardService) ReplaceDashboardCells(ctx context.Context, id platform.ID, cs []*influxdb.Cell) error { return s.Client. PutJSON(cs, cellPath(id)). // TODO: previous implementation did not do anything with the response except validate it is valid json. @@ -1079,18 +1082,18 @@ func (s *DashboardService) ReplaceDashboardCells(ctx context.Context, id influxd Do(ctx) } -func dashboardIDPath(id influxdb.ID) string { +func dashboardIDPath(id platform.ID) string { return path.Join(prefixDashboards, id.String()) } -func cellPath(id influxdb.ID) string { +func cellPath(id platform.ID) string { return path.Join(dashboardIDPath(id), "cells") } -func cellViewPath(dashboardID, cellID influxdb.ID) string { +func cellViewPath(dashboardID, cellID platform.ID) string { return path.Join(dashboardCellIDPath(dashboardID, cellID), "view") } -func dashboardCellIDPath(id influxdb.ID, cellID influxdb.ID) string { +func dashboardCellIDPath(id platform.ID, cellID platform.ID) string { return path.Join(cellPath(id), cellID.String()) } diff --git a/dashboards/transport/http_test.go b/dashboards/transport/http_test.go index 547966c2abb..c2c9c6ed217 100644 --- a/dashboards/transport/http_test.go +++ b/dashboards/transport/http_test.go @@ -12,6 +12,9 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" @@ -419,10 +422,10 @@ func TestService_handleGetDashboard(t *testing.T) { name: "get a dashboard by id with view properties", fields: fields{ &mock.DashboardService{ - GetDashboardCellViewF: func(ctx context.Context, dashboardID influxdb.ID, cellID influxdb.ID) (*influxdb.View, error) { + GetDashboardCellViewF: func(ctx context.Context, dashboardID platform.ID, cellID platform.ID) (*influxdb.View, error) { return &influxdb.View{ViewContents: influxdb.ViewContents{Name: "the cell name"}, Properties: influxdb.XYViewProperties{Type: influxdb.ViewPropertyTypeXY}}, nil }, - FindDashboardByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { + FindDashboardByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Dashboard, error) { if id == dashboardstesting.MustIDBase16("020f755c3c082000") { return &influxdb.Dashboard{ ID: dashboardstesting.MustIDBase16("020f755c3c082000"), @@ -529,10 +532,10 @@ func TestService_handleGetDashboard(t *testing.T) { name: "get a dashboard by id with view properties, but a cell doesnt exist", fields: fields{ &mock.DashboardService{ - GetDashboardCellViewF: func(ctx context.Context, dashboardID influxdb.ID, cellID influxdb.ID) (*influxdb.View, error) { + GetDashboardCellViewF: func(ctx context.Context, dashboardID platform.ID, cellID platform.ID) (*influxdb.View, error) { return nil, nil }, - FindDashboardByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { + FindDashboardByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Dashboard, error) { if id == dashboardstesting.MustIDBase16("020f755c3c082000") { return &influxdb.Dashboard{ ID: dashboardstesting.MustIDBase16("020f755c3c082000"), @@ -609,10 +612,10 @@ func TestService_handleGetDashboard(t *testing.T) { name: "get a dashboard by id doesnt return cell properties if they exist by default", fields: fields{ &mock.DashboardService{ - GetDashboardCellViewF: func(ctx context.Context, dashboardID influxdb.ID, cellID influxdb.ID) (*influxdb.View, error) { + GetDashboardCellViewF: func(ctx context.Context, dashboardID platform.ID, cellID platform.ID) (*influxdb.View, error) { return &influxdb.View{ViewContents: influxdb.ViewContents{Name: "the cell name"}, Properties: influxdb.XYViewProperties{Type: influxdb.ViewPropertyTypeXY}}, nil }, - FindDashboardByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { + FindDashboardByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Dashboard, error) { if id == dashboardstesting.MustIDBase16("020f755c3c082000") { return &influxdb.Dashboard{ ID: dashboardstesting.MustIDBase16("020f755c3c082000"), @@ -687,7 +690,7 @@ func TestService_handleGetDashboard(t *testing.T) { name: "get a dashboard by id", fields: fields{ &mock.DashboardService{ - FindDashboardByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { + FindDashboardByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Dashboard, error) { if id == dashboardstesting.MustIDBase16("020f755c3c082000") { return &influxdb.Dashboard{ ID: dashboardstesting.MustIDBase16("020f755c3c082000"), @@ -761,9 +764,9 @@ func TestService_handleGetDashboard(t *testing.T) { name: "not found", fields: fields{ &mock.DashboardService{ - FindDashboardByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + FindDashboardByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Dashboard, error) { + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrDashboardNotFound, } }, @@ -1112,7 +1115,7 @@ func TestService_handleDeleteDashboard(t *testing.T) { name: "remove a dashboard by id", fields: fields{ &mock.DashboardService{ - DeleteDashboardF: func(ctx context.Context, id influxdb.ID) error { + DeleteDashboardF: func(ctx context.Context, id platform.ID) error { if id == dashboardstesting.MustIDBase16("020f755c3c082000") { return nil } @@ -1132,9 +1135,9 @@ func TestService_handleDeleteDashboard(t *testing.T) { name: "dashboard not found", fields: fields{ &mock.DashboardService{ - DeleteDashboardF: func(ctx context.Context, id influxdb.ID) error { - return &influxdb.Error{ - Code: influxdb.ENotFound, + DeleteDashboardF: func(ctx context.Context, id platform.ID) error { + return &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrDashboardNotFound, } }, @@ -1214,7 +1217,7 @@ func TestService_handlePatchDashboard(t *testing.T) { name: "update a dashboard name", fields: fields{ &mock.DashboardService{ - UpdateDashboardF: func(ctx context.Context, id influxdb.ID, upd influxdb.DashboardUpdate) (*influxdb.Dashboard, error) { + UpdateDashboardF: func(ctx context.Context, id platform.ID, upd influxdb.DashboardUpdate) (*influxdb.Dashboard, error) { if id == dashboardstesting.MustIDBase16("020f755c3c082000") { d := &influxdb.Dashboard{ ID: dashboardstesting.MustIDBase16("020f755c3c082000"), @@ -1295,7 +1298,7 @@ func TestService_handlePatchDashboard(t *testing.T) { name: "update a dashboard with empty request body", fields: fields{ &mock.DashboardService{ - UpdateDashboardF: func(ctx context.Context, id influxdb.ID, upd influxdb.DashboardUpdate) (*influxdb.Dashboard, error) { + UpdateDashboardF: func(ctx context.Context, id platform.ID, upd influxdb.DashboardUpdate) (*influxdb.Dashboard, error) { return nil, fmt.Errorf("not found") }, }, @@ -1311,9 +1314,9 @@ func TestService_handlePatchDashboard(t *testing.T) { name: "dashboard not found", fields: fields{ &mock.DashboardService{ - UpdateDashboardF: func(ctx context.Context, id influxdb.ID, upd influxdb.DashboardUpdate) (*influxdb.Dashboard, error) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + UpdateDashboardF: func(ctx context.Context, id platform.ID, upd influxdb.DashboardUpdate) (*influxdb.Dashboard, error) { + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrDashboardNotFound, } }, @@ -1405,7 +1408,7 @@ func TestService_handlePostDashboardCell(t *testing.T) { name: "empty body", fields: fields{ &mock.DashboardService{ - AddDashboardCellF: func(ctx context.Context, id influxdb.ID, c *influxdb.Cell, opt influxdb.AddDashboardCellOptions) error { + AddDashboardCellF: func(ctx context.Context, id platform.ID, c *influxdb.Cell, opt influxdb.AddDashboardCellOptions) error { c.ID = dashboardstesting.MustIDBase16("020f755c3c082000") return nil }, @@ -1424,7 +1427,7 @@ func TestService_handlePostDashboardCell(t *testing.T) { name: "no properties", fields: fields{ &mock.DashboardService{ - AddDashboardCellF: func(ctx context.Context, id influxdb.ID, c *influxdb.Cell, opt influxdb.AddDashboardCellOptions) error { + AddDashboardCellF: func(ctx context.Context, id platform.ID, c *influxdb.Cell, opt influxdb.AddDashboardCellOptions) error { c.ID = dashboardstesting.MustIDBase16("020f755c3c082000") return nil }, @@ -1448,7 +1451,7 @@ func TestService_handlePostDashboardCell(t *testing.T) { name: "bad dash id", fields: fields{ &mock.DashboardService{ - AddDashboardCellF: func(ctx context.Context, id influxdb.ID, c *influxdb.Cell, opt influxdb.AddDashboardCellOptions) error { + AddDashboardCellF: func(ctx context.Context, id platform.ID, c *influxdb.Cell, opt influxdb.AddDashboardCellOptions) error { c.ID = dashboardstesting.MustIDBase16("020f755c3c082000") return nil }, @@ -1472,11 +1475,11 @@ func TestService_handlePostDashboardCell(t *testing.T) { name: "general create a dashboard cell", fields: fields{ &mock.DashboardService{ - AddDashboardCellF: func(ctx context.Context, id influxdb.ID, c *influxdb.Cell, opt influxdb.AddDashboardCellOptions) error { + AddDashboardCellF: func(ctx context.Context, id platform.ID, c *influxdb.Cell, opt influxdb.AddDashboardCellOptions) error { c.ID = dashboardstesting.MustIDBase16("020f755c3c082000") return nil }, - GetDashboardCellViewF: func(ctx context.Context, id1, id2 influxdb.ID) (*influxdb.View, error) { + GetDashboardCellViewF: func(ctx context.Context, id1, id2 platform.ID) (*influxdb.View, error) { return &influxdb.View{ ViewContents: influxdb.ViewContents{ ID: dashboardstesting.MustIDBase16("020f755c3c082001"), @@ -1576,7 +1579,7 @@ func TestService_handleDeleteDashboardCell(t *testing.T) { name: "remove a dashboard cell", fields: fields{ &mock.DashboardService{ - RemoveDashboardCellF: func(ctx context.Context, id influxdb.ID, cellID influxdb.ID) error { + RemoveDashboardCellF: func(ctx context.Context, id platform.ID, cellID platform.ID) error { return nil }, }, @@ -1662,7 +1665,7 @@ func TestService_handlePatchDashboardCell(t *testing.T) { name: "update a dashboard cell", fields: fields{ &mock.DashboardService{ - UpdateDashboardCellF: func(ctx context.Context, id, cellID influxdb.ID, upd influxdb.CellUpdate) (*influxdb.Cell, error) { + UpdateDashboardCellF: func(ctx context.Context, id, cellID platform.ID, upd influxdb.CellUpdate) (*influxdb.Cell, error) { cell := &influxdb.Cell{ ID: dashboardstesting.MustIDBase16("020f755c3c082000"), } @@ -1764,12 +1767,12 @@ func TestService_handlePatchDashboardCell(t *testing.T) { func Test_dashboardCellIDPath(t *testing.T) { t.Parallel() - dashboard, err := influxdb.IDFromString("deadbeefdeadbeef") + dashboard, err := platform.IDFromString("deadbeefdeadbeef") if err != nil { t.Fatal(err) } - cell, err := influxdb.IDFromString("cade9a7ecade9a7e") + cell, err := platform.IDFromString("cade9a7ecade9a7e") if err != nil { t.Fatal(err) } @@ -1833,7 +1836,7 @@ func TestService_handlePostDashboardLabel(t *testing.T) { } type args struct { labelMapping *influxdb.LabelMapping - dashboardID influxdb.ID + dashboardID platform.ID } type wants struct { statusCode int @@ -1851,7 +1854,7 @@ func TestService_handlePostDashboardLabel(t *testing.T) { name: "add label to dashboard", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, Name: "label", @@ -1897,10 +1900,10 @@ func TestService_handlePostDashboardLabel(t *testing.T) { zaptest.NewLogger(t), withLabelService(tt.fields.LabelService), withDashboardService(&mock.DashboardService{ - FindDashboardByIDF: func(_ context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { + FindDashboardByIDF: func(_ context.Context, id platform.ID) (*influxdb.Dashboard, error) { return &influxdb.Dashboard{ ID: id, - OrganizationID: influxdb.ID(25), + OrganizationID: platform.ID(25), }, nil }, }), diff --git a/dbrp/bucket_service.go b/dbrp/bucket_service.go index 2f623968d22..7ec97c8f0b2 100644 --- a/dbrp/bucket_service.go +++ b/dbrp/bucket_service.go @@ -3,6 +3,8 @@ package dbrp import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "go.uber.org/zap" ) @@ -21,7 +23,7 @@ func NewBucketService(logger *zap.Logger, bucketService influxdb.BucketService, } } -func (s *BucketService) DeleteBucket(ctx context.Context, id influxdb.ID) error { +func (s *BucketService) DeleteBucket(ctx context.Context, id platform.ID) error { bucket, err := s.BucketService.FindBucketByID(ctx, id) if err != nil { return err diff --git a/dbrp/error.go b/dbrp/error.go index cb20747a9df..d71344c0175 100644 --- a/dbrp/error.go +++ b/dbrp/error.go @@ -3,39 +3,41 @@ package dbrp import ( "fmt" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) var ( // ErrDBRPNotFound is used when the specified DBRP cannot be found. - ErrDBRPNotFound = &influxdb.Error{ - Code: influxdb.ENotFound, + ErrDBRPNotFound = &errors.Error{ + Code: errors.ENotFound, Msg: "unable to find DBRP", } // ErrNotUniqueID is used when the ID of the DBRP is not unique. - ErrNotUniqueID = &influxdb.Error{ - Code: influxdb.EConflict, + ErrNotUniqueID = &errors.Error{ + Code: errors.EConflict, Msg: "ID already exists", } // ErrFailureGeneratingID occurs ony when the random number generator // cannot generate an ID in MaxIDGenerationN times. - ErrFailureGeneratingID = &influxdb.Error{ - Code: influxdb.EInternal, + ErrFailureGeneratingID = &errors.Error{ + Code: errors.EInternal, Msg: "unable to generate valid id", } - ErrNoOrgProvided = &influxdb.Error{ - Code: influxdb.EInvalid, + ErrNoOrgProvided = &errors.Error{ + Code: errors.EInvalid, Msg: "either 'org' or 'orgID' must be provided", } ) // ErrOrgNotFound returns a more informative error about a 404 on org name. func ErrOrgNotFound(org string) error { - return &influxdb.Error{ - Code: influxdb.ENotFound, + return &errors.Error{ + Code: errors.ENotFound, Msg: fmt.Sprintf("invalid org %q", org), Err: influxdb.ErrOrgNotFound, } @@ -44,8 +46,8 @@ func ErrOrgNotFound(org string) error { // ErrInvalidOrgID returns a more informative error about a failure // to decode an organization ID. func ErrInvalidOrgID(id string, err error) error { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("invalid org ID %q", id), Err: err, } @@ -54,8 +56,8 @@ func ErrInvalidOrgID(id string, err error) error { // ErrInvalidBucketID returns a more informative error about a failure // to decode a bucket ID. func ErrInvalidBucketID(id string, err error) error { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("invalid bucket ID %q", id), Err: err, } @@ -63,37 +65,37 @@ func ErrInvalidBucketID(id string, err error) error { // ErrInvalidDBRPID is used when the ID of the DBRP cannot be encoded. func ErrInvalidDBRPID(id string, err error) error { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("invalid DBRP ID %q", id), Err: err, } } // ErrInvalidDBRP is used when a service was provided an invalid DBRP. -func ErrInvalidDBRP(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInvalid, +func ErrInvalidDBRP(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInvalid, Msg: "DBRP provided is invalid", Err: err, } } // ErrInternalService is used when the error comes from an internal system. -func ErrInternalService(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func ErrInternalService(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Err: err, } } // ErrDBRPAlreadyExists is used when there is a conflict in creating a new DBRP. -func ErrDBRPAlreadyExists(msg string) *influxdb.Error { +func ErrDBRPAlreadyExists(msg string) *errors.Error { if msg == "" { msg = "DBRP already exists" } - return &influxdb.Error{ - Code: influxdb.EConflict, + return &errors.Error{ + Code: errors.EConflict, Msg: msg, } } diff --git a/dbrp/http_client_dbrp.go b/dbrp/http_client_dbrp.go index 56ce6ff8183..a198603c0c3 100644 --- a/dbrp/http_client_dbrp.go +++ b/dbrp/http_client_dbrp.go @@ -6,6 +6,8 @@ import ( "path" "strconv" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/tracing" "github.com/influxdata/influxdb/v2/pkg/httpc" @@ -26,11 +28,11 @@ func NewClient(client *httpc.Client) *Client { } } -func (c *Client) dbrpURL(id influxdb.ID) string { +func (c *Client) dbrpURL(id platform.ID) string { return path.Join(c.Prefix, id.String()) } -func (c *Client) FindByID(ctx context.Context, orgID, id influxdb.ID) (*influxdb.DBRPMappingV2, error) { +func (c *Client) FindByID(ctx context.Context, orgID, id platform.ID) (*influxdb.DBRPMappingV2, error) { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -123,7 +125,7 @@ func (c *Client) Update(ctx context.Context, dbrp *influxdb.DBRPMappingV2) error return nil } -func (c *Client) Delete(ctx context.Context, orgID, id influxdb.ID) error { +func (c *Client) Delete(ctx context.Context, orgID, id platform.ID) error { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() diff --git a/dbrp/http_client_dbrp_test.go b/dbrp/http_client_dbrp_test.go index 8fc17c7f7a0..c17179fc93d 100644 --- a/dbrp/http_client_dbrp_test.go +++ b/dbrp/http_client_dbrp_test.go @@ -2,6 +2,7 @@ package dbrp_test import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" "net/http/httptest" "testing" @@ -20,7 +21,7 @@ func setup(t *testing.T) (*dbrp.Client, func()) { dbrp.ID = 1 return nil }, - FindByIDFn: func(ctx context.Context, orgID, id influxdb.ID) (*influxdb.DBRPMappingV2, error) { + FindByIDFn: func(ctx context.Context, orgID, id platform.ID) (*influxdb.DBRPMappingV2, error) { return &influxdb.DBRPMappingV2{ ID: id, Database: "db", @@ -77,7 +78,7 @@ func TestClient(t *testing.T) { if _, err := client.FindByID(context.Background(), 1, 1); err != nil { t.Error(err) } - oid := influxdb.ID(1) + oid := platform.ID(1) if _, _, err := client.FindMany(context.Background(), influxdb.DBRPMappingFilterV2{OrgID: &oid}); err != nil { t.Error(err) } diff --git a/dbrp/http_server_dbrp.go b/dbrp/http_server_dbrp.go index a2c82912d9a..89549cb2ed9 100644 --- a/dbrp/http_server_dbrp.go +++ b/dbrp/http_server_dbrp.go @@ -5,6 +5,9 @@ import ( "net/http" "strconv" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/influxdata/influxdb/v2" @@ -77,16 +80,16 @@ func (h *Handler) handlePostDBRP(w http.ResponseWriter, r *http.Request) { ctx := r.Context() var req createDBRPRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - h.api.Err(w, r, &influxdb.Error{ - Code: influxdb.EInvalid, + h.api.Err(w, r, &errors.Error{ + Code: errors.EInvalid, Msg: "invalid json structure", Err: err, }) return } - var orgID influxdb.ID - var bucketID influxdb.ID + var orgID platform.ID + var bucketID platform.ID if req.OrganizationID == "" { if req.Org == "" { @@ -154,14 +157,14 @@ func (h *Handler) handleGetDBRP(w http.ResponseWriter, r *http.Request) { ctx := r.Context() id := chi.URLParam(r, "id") if id == "" { - h.api.Err(w, r, &influxdb.Error{ - Code: influxdb.EInvalid, + h.api.Err(w, r, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", }) return } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { h.api.Err(w, r, err) return @@ -193,14 +196,14 @@ func (h *Handler) handlePatchDBRP(w http.ResponseWriter, r *http.Request) { id := chi.URLParam(r, "id") if id == "" { - h.api.Err(w, r, &influxdb.Error{ - Code: influxdb.EInvalid, + h.api.Err(w, r, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", }) return } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { h.api.Err(w, r, err) return @@ -219,8 +222,8 @@ func (h *Handler) handlePatchDBRP(w http.ResponseWriter, r *http.Request) { } if err := json.NewDecoder(r.Body).Decode(&bodyRequest); err != nil { - h.api.Err(w, r, &influxdb.Error{ - Code: influxdb.EInvalid, + h.api.Err(w, r, &errors.Error{ + Code: errors.EInvalid, Msg: "invalid json structure", Err: err, }) @@ -251,14 +254,14 @@ func (h *Handler) handleDeleteDBRP(w http.ResponseWriter, r *http.Request) { ctx := r.Context() id := chi.URLParam(r, "id") if id == "" { - h.api.Err(w, r, &influxdb.Error{ - Code: influxdb.EInvalid, + h.api.Err(w, r, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", }) return } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { h.api.Err(w, r, err) return @@ -304,8 +307,8 @@ func (h *Handler) getFilterFromHTTPRequest(r *http.Request) (f influxdb.DBRPMapp if rawDefault != "" { d, err := strconv.ParseBool(rawDefault) if err != nil { - return f, &influxdb.Error{ - Code: influxdb.EInvalid, + return f, &errors.Error{ + Code: errors.EInvalid, Msg: "invalid default parameter", } } @@ -314,8 +317,8 @@ func (h *Handler) getFilterFromHTTPRequest(r *http.Request) (f influxdb.DBRPMapp return f, nil } -func getIDFromHTTPRequest(r *http.Request, key string, onErr func(string, error) error) (*influxdb.ID, error) { - var id influxdb.ID +func getIDFromHTTPRequest(r *http.Request, key string, onErr func(string, error) error) (*platform.ID, error) { + var id platform.ID raw := r.URL.Query().Get(key) if raw != "" { if err := id.DecodeFromString(raw); err != nil { @@ -329,7 +332,7 @@ func getIDFromHTTPRequest(r *http.Request, key string, onErr func(string, error) // mustGetOrgIDFromHTTPRequest returns the org ID parameter from the request, falling // back to looking up the org ID by org name if the ID parameter is not present. -func (h *Handler) mustGetOrgIDFromHTTPRequest(r *http.Request) (*influxdb.ID, error) { +func (h *Handler) mustGetOrgIDFromHTTPRequest(r *http.Request) (*platform.ID, error) { orgID, err := getIDFromHTTPRequest(r, "orgID", ErrInvalidOrgID) if err != nil { return nil, err @@ -350,10 +353,10 @@ func (h *Handler) mustGetOrgIDFromHTTPRequest(r *http.Request) (*influxdb.ID, er return orgID, nil } -func getDBRPIDFromHTTPRequest(r *http.Request) (*influxdb.ID, error) { +func getDBRPIDFromHTTPRequest(r *http.Request) (*platform.ID, error) { return getIDFromHTTPRequest(r, "id", ErrInvalidDBRPID) } -func getBucketIDFromHTTPRequest(r *http.Request) (*influxdb.ID, error) { +func getBucketIDFromHTTPRequest(r *http.Request) (*platform.ID, error) { return getIDFromHTTPRequest(r, "bucketID", ErrInvalidBucketID) } diff --git a/dbrp/http_server_dbrp_test.go b/dbrp/http_server_dbrp_test.go index 996efea5586..b5ad43ed5ed 100644 --- a/dbrp/http_server_dbrp_test.go +++ b/dbrp/http_server_dbrp_test.go @@ -4,6 +4,8 @@ import ( "context" "encoding/json" "errors" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" "io" "io/ioutil" "net/http" @@ -102,7 +104,7 @@ func Test_handlePostDBRP(t *testing.T) { "retention_policy": "autogen", "default": false }`), - ExpectedErr: dbrp.ErrInvalidOrgID("invalid", influxdb.ErrInvalidIDLength), + ExpectedErr: dbrp.ErrInvalidOrgID("invalid", platform.ErrInvalidIDLength), }, { Name: "Create with invalid org name", @@ -124,7 +126,7 @@ func Test_handlePostDBRP(t *testing.T) { "retention_policy": "autogen", "default": false }`), - ExpectedErr: dbrp.ErrInvalidBucketID("invalid", influxdb.ErrInvalidIDLength), + ExpectedErr: dbrp.ErrInvalidBucketID("invalid", platform.ErrInvalidIDLength), }, } @@ -148,7 +150,7 @@ func Test_handlePostDBRP(t *testing.T) { if err != nil { t.Fatal(err) } - var actualErr influxdb.Error + var actualErr errors2.Error if err := json.Unmarshal(b, &actualErr); err != nil { t.Fatal(err) } @@ -200,18 +202,18 @@ func Test_handleGetDBRPs(t *testing.T) { { Name: "invalid org", QueryParams: "orgID=invalid", - ExpectedErr: dbrp.ErrInvalidOrgID("invalid", influxdb.ErrInvalidIDLength), + ExpectedErr: dbrp.ErrInvalidOrgID("invalid", platform.ErrInvalidIDLength), }, { Name: "invalid bucket", QueryParams: "orgID=059af7ed2a034000&bucketID=invalid", - ExpectedErr: dbrp.ErrInvalidBucketID("invalid", influxdb.ErrInvalidIDLength), + ExpectedErr: dbrp.ErrInvalidBucketID("invalid", platform.ErrInvalidIDLength), }, { Name: "invalid default", QueryParams: "orgID=059af7ed2a034000&default=notabool", - ExpectedErr: &influxdb.Error{ - Code: influxdb.EInvalid, + ExpectedErr: &errors2.Error{ + Code: errors2.EInvalid, Msg: "invalid default parameter", }, }, @@ -290,7 +292,7 @@ func Test_handleGetDBRPs(t *testing.T) { if err != nil { t.Fatal(err) } - var actualErr influxdb.Error + var actualErr errors2.Error if err := json.Unmarshal(b, &actualErr); err != nil { t.Fatal(err) } @@ -363,7 +365,7 @@ func Test_handlePatchDBRP(t *testing.T) { Input: strings.NewReader(`{ "database": "updatedb" }`), - ExpectedErr: dbrp.ErrInvalidOrgID("invalid", influxdb.ErrInvalidIDLength), + ExpectedErr: dbrp.ErrInvalidOrgID("invalid", platform.ErrInvalidIDLength), }, { Name: "no org", @@ -418,7 +420,7 @@ func Test_handlePatchDBRP(t *testing.T) { if err != nil { t.Fatal(err) } - var actualErr influxdb.Error + var actualErr errors2.Error if err := json.Unmarshal(b, &actualErr); err != nil { t.Fatal(err) } @@ -459,7 +461,7 @@ func Test_handleDeleteDBRP(t *testing.T) { { Name: "invalid org", URLSuffix: "/1111111111111111?orgID=invalid", - ExpectedErr: dbrp.ErrInvalidOrgID("invalid", influxdb.ErrInvalidIDLength), + ExpectedErr: dbrp.ErrInvalidOrgID("invalid", platform.ErrInvalidIDLength), }, { Name: "invalid org name", @@ -511,7 +513,7 @@ func Test_handleDeleteDBRP(t *testing.T) { if err != nil { t.Fatal(err) } - var actualErr influxdb.Error + var actualErr errors2.Error if err := json.Unmarshal(b, &actualErr); err != nil { t.Fatal(err) } diff --git a/dbrp/middleware_auth.go b/dbrp/middleware_auth.go index d9556ffd866..cc98a124c60 100644 --- a/dbrp/middleware_auth.go +++ b/dbrp/middleware_auth.go @@ -3,6 +3,8 @@ package dbrp import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/authorizer" ) @@ -17,7 +19,7 @@ func NewAuthorizedService(s influxdb.DBRPMappingServiceV2) *AuthorizedService { return &AuthorizedService{DBRPMappingServiceV2: s} } -func (svc AuthorizedService) FindByID(ctx context.Context, orgID, id influxdb.ID) (*influxdb.DBRPMappingV2, error) { +func (svc AuthorizedService) FindByID(ctx context.Context, orgID, id platform.ID) (*influxdb.DBRPMappingV2, error) { mapping, err := svc.DBRPMappingServiceV2.FindByID(ctx, orgID, id) if err != nil { return nil, err @@ -50,7 +52,7 @@ func (svc AuthorizedService) Update(ctx context.Context, u *influxdb.DBRPMapping return svc.DBRPMappingServiceV2.Update(ctx, u) } -func (svc AuthorizedService) Delete(ctx context.Context, orgID, id influxdb.ID) error { +func (svc AuthorizedService) Delete(ctx context.Context, orgID, id platform.ID) error { mapping, err := svc.DBRPMappingServiceV2.FindByID(ctx, orgID, id) if err != nil { return err diff --git a/dbrp/middleware_auth_test.go b/dbrp/middleware_auth_test.go index c3a2e8a354b..23fc0d0cbee 100644 --- a/dbrp/middleware_auth_test.go +++ b/dbrp/middleware_auth_test.go @@ -2,6 +2,8 @@ package dbrp_test import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "testing" "github.com/google/go-cmp/cmp" @@ -17,8 +19,8 @@ func TestAuth_FindByID(t *testing.T) { service influxdb.DBRPMappingServiceV2 } type args struct { - orgID influxdb.ID - id influxdb.ID + orgID platform.ID + id platform.ID permission influxdb.Permission } type wants struct { @@ -35,10 +37,10 @@ func TestAuth_FindByID(t *testing.T) { name: "authorized to access id by org id", fields: fields{ service: &mock.DBRPMappingServiceV2{ - FindByIDFn: func(_ context.Context, _, _ influxdb.ID) (*influxdb.DBRPMappingV2, error) { + FindByIDFn: func(_ context.Context, _, _ platform.ID) (*influxdb.DBRPMappingV2, error) { return &influxdb.DBRPMappingV2{ - OrganizationID: influxdb.ID(1), - BucketID: influxdb.ID(1), + OrganizationID: platform.ID(1), + BucketID: platform.ID(1), }, nil }, }, @@ -62,10 +64,10 @@ func TestAuth_FindByID(t *testing.T) { name: "authorized to access id by id", fields: fields{ service: &mock.DBRPMappingServiceV2{ - FindByIDFn: func(_ context.Context, _, _ influxdb.ID) (*influxdb.DBRPMappingV2, error) { + FindByIDFn: func(_ context.Context, _, _ platform.ID) (*influxdb.DBRPMappingV2, error) { return &influxdb.DBRPMappingV2{ - OrganizationID: influxdb.ID(1), - BucketID: influxdb.ID(1), + OrganizationID: platform.ID(1), + BucketID: platform.ID(1), }, nil }, }, @@ -89,10 +91,10 @@ func TestAuth_FindByID(t *testing.T) { name: "unauthorized to access id by org id", fields: fields{ service: &mock.DBRPMappingServiceV2{ - FindByIDFn: func(_ context.Context, _, _ influxdb.ID) (*influxdb.DBRPMappingV2, error) { + FindByIDFn: func(_ context.Context, _, _ platform.ID) (*influxdb.DBRPMappingV2, error) { return &influxdb.DBRPMappingV2{ - OrganizationID: influxdb.ID(2), - BucketID: influxdb.ID(1), + OrganizationID: platform.ID(2), + BucketID: platform.ID(1), }, nil }, }, @@ -109,9 +111,9 @@ func TestAuth_FindByID(t *testing.T) { orgID: 2, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/0000000000000002/buckets/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -119,10 +121,10 @@ func TestAuth_FindByID(t *testing.T) { name: "unauthorized to access id by id", fields: fields{ service: &mock.DBRPMappingServiceV2{ - FindByIDFn: func(_ context.Context, _, _ influxdb.ID) (*influxdb.DBRPMappingV2, error) { + FindByIDFn: func(_ context.Context, _, _ platform.ID) (*influxdb.DBRPMappingV2, error) { return &influxdb.DBRPMappingV2{ - OrganizationID: influxdb.ID(1), - BucketID: influxdb.ID(1), + OrganizationID: platform.ID(1), + BucketID: platform.ID(1), }, nil }, }, @@ -139,9 +141,9 @@ func TestAuth_FindByID(t *testing.T) { orgID: 2, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/0000000000000002/buckets/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -446,9 +448,9 @@ func TestAuth_Create(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/0000000000000001/buckets/0000000000000002 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -472,8 +474,8 @@ func TestAuth_Update(t *testing.T) { service influxdb.DBRPMappingServiceV2 } type args struct { - orgID influxdb.ID - id influxdb.ID + orgID platform.ID + id platform.ID permission influxdb.Permission } type wants struct { @@ -523,9 +525,9 @@ func TestAuth_Update(t *testing.T) { orgID: 1, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/0000000000000001/buckets/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -550,8 +552,8 @@ func TestAuth_Delete(t *testing.T) { service influxdb.DBRPMappingServiceV2 } type args struct { - orgID influxdb.ID - id influxdb.ID + orgID platform.ID + id platform.ID permission influxdb.Permission } type wants struct { @@ -568,10 +570,10 @@ func TestAuth_Delete(t *testing.T) { name: "authorized", fields: fields{ service: &mock.DBRPMappingServiceV2{ - FindByIDFn: func(_ context.Context, _, _ influxdb.ID) (*influxdb.DBRPMappingV2, error) { + FindByIDFn: func(_ context.Context, _, _ platform.ID) (*influxdb.DBRPMappingV2, error) { return &influxdb.DBRPMappingV2{ - OrganizationID: influxdb.ID(1), - BucketID: influxdb.ID(1), + OrganizationID: platform.ID(1), + BucketID: platform.ID(1), }, nil }, }, @@ -595,10 +597,10 @@ func TestAuth_Delete(t *testing.T) { name: "unauthorized", fields: fields{ service: &mock.DBRPMappingServiceV2{ - FindByIDFn: func(_ context.Context, _, _ influxdb.ID) (*influxdb.DBRPMappingV2, error) { + FindByIDFn: func(_ context.Context, _, _ platform.ID) (*influxdb.DBRPMappingV2, error) { return &influxdb.DBRPMappingV2{ - OrganizationID: influxdb.ID(1), - BucketID: influxdb.ID(1), + OrganizationID: platform.ID(1), + BucketID: platform.ID(1), }, nil }, }, @@ -615,9 +617,9 @@ func TestAuth_Delete(t *testing.T) { orgID: 1, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/0000000000000001/buckets/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, diff --git a/dbrp/mocks/bucket_service.go b/dbrp/mocks/bucket_service.go index 0b07f351c17..07a18d13d88 100644 --- a/dbrp/mocks/bucket_service.go +++ b/dbrp/mocks/bucket_service.go @@ -8,6 +8,7 @@ import ( context "context" gomock "github.com/golang/mock/gomock" influxdb "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" reflect "reflect" ) @@ -49,7 +50,7 @@ func (mr *MockBucketServiceMockRecorder) CreateBucket(arg0, arg1 interface{}) *g } // DeleteBucket mocks base method -func (m *MockBucketService) DeleteBucket(arg0 context.Context, arg1 influxdb.ID) error { +func (m *MockBucketService) DeleteBucket(arg0 context.Context, arg1 platform.ID) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteBucket", arg0, arg1) ret0, _ := ret[0].(error) @@ -78,7 +79,7 @@ func (mr *MockBucketServiceMockRecorder) FindBucket(arg0, arg1 interface{}) *gom } // FindBucketByID mocks base method -func (m *MockBucketService) FindBucketByID(arg0 context.Context, arg1 influxdb.ID) (*influxdb.Bucket, error) { +func (m *MockBucketService) FindBucketByID(arg0 context.Context, arg1 platform.ID) (*influxdb.Bucket, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "FindBucketByID", arg0, arg1) ret0, _ := ret[0].(*influxdb.Bucket) @@ -93,7 +94,7 @@ func (mr *MockBucketServiceMockRecorder) FindBucketByID(arg0, arg1 interface{}) } // FindBucketByName mocks base method -func (m *MockBucketService) FindBucketByName(arg0 context.Context, arg1 influxdb.ID, arg2 string) (*influxdb.Bucket, error) { +func (m *MockBucketService) FindBucketByName(arg0 context.Context, arg1 platform.ID, arg2 string) (*influxdb.Bucket, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "FindBucketByName", arg0, arg1, arg2) ret0, _ := ret[0].(*influxdb.Bucket) @@ -129,7 +130,7 @@ func (mr *MockBucketServiceMockRecorder) FindBuckets(arg0, arg1 interface{}, arg } // UpdateBucket mocks base method -func (m *MockBucketService) UpdateBucket(arg0 context.Context, arg1 influxdb.ID, arg2 influxdb.BucketUpdate) (*influxdb.Bucket, error) { +func (m *MockBucketService) UpdateBucket(arg0 context.Context, arg1 platform.ID, arg2 influxdb.BucketUpdate) (*influxdb.Bucket, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "UpdateBucket", arg0, arg1, arg2) ret0, _ := ret[0].(*influxdb.Bucket) diff --git a/dbrp/mocks/dbrp_mapping_service_v2.go b/dbrp/mocks/dbrp_mapping_service_v2.go index b6c40577d46..5e3f1e92d7f 100644 --- a/dbrp/mocks/dbrp_mapping_service_v2.go +++ b/dbrp/mocks/dbrp_mapping_service_v2.go @@ -8,6 +8,7 @@ import ( context "context" gomock "github.com/golang/mock/gomock" influxdb "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" reflect "reflect" ) @@ -49,7 +50,7 @@ func (mr *MockDBRPMappingServiceV2MockRecorder) Create(arg0, arg1 interface{}) * } // Delete mocks base method -func (m *MockDBRPMappingServiceV2) Delete(arg0 context.Context, arg1, arg2 influxdb.ID) error { +func (m *MockDBRPMappingServiceV2) Delete(arg0 context.Context, arg1, arg2 platform.ID) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Delete", arg0, arg1, arg2) ret0, _ := ret[0].(error) @@ -63,7 +64,7 @@ func (mr *MockDBRPMappingServiceV2MockRecorder) Delete(arg0, arg1, arg2 interfac } // FindByID mocks base method -func (m *MockDBRPMappingServiceV2) FindByID(arg0 context.Context, arg1, arg2 influxdb.ID) (*influxdb.DBRPMappingV2, error) { +func (m *MockDBRPMappingServiceV2) FindByID(arg0 context.Context, arg1, arg2 platform.ID) (*influxdb.DBRPMappingV2, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "FindByID", arg0, arg1, arg2) ret0, _ := ret[0].(*influxdb.DBRPMappingV2) diff --git a/dbrp/service.go b/dbrp/service.go index 4747423dc14..2ed92d84d5b 100644 --- a/dbrp/service.go +++ b/dbrp/service.go @@ -29,6 +29,8 @@ import ( "context" "encoding/json" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" "github.com/influxdata/influxdb/v2/snowflake" @@ -45,7 +47,7 @@ var _ influxdb.DBRPMappingServiceV2 = (*AuthorizedService)(nil) type Service struct { store kv.Store - IDGen influxdb.IDGenerator + IDGen platform.IDGenerator bucketSvc influxdb.BucketService byOrgAndDatabase *kv.Index @@ -56,7 +58,7 @@ func indexForeignKey(dbrp influxdb.DBRPMappingV2) []byte { return composeForeignKey(dbrp.OrganizationID, dbrp.Database) } -func composeForeignKey(orgID influxdb.ID, db string) []byte { +func composeForeignKey(orgID platform.ID, db string) []byte { encID, _ := orgID.Encode() key := make([]byte, len(encID)+len(db)) copy(key, encID) @@ -94,12 +96,12 @@ func (s *Service) getDefault(tx kv.Tx, compKey []byte) ([]byte, error) { } // getDefaultID returns the default mapping ID for the given orgID and db. -func (s *Service) getDefaultID(tx kv.Tx, compKey []byte) (influxdb.ID, error) { +func (s *Service) getDefaultID(tx kv.Tx, compKey []byte) (platform.ID, error) { defID, err := s.getDefault(tx, compKey) if err != nil { return 0, err } - id := new(influxdb.ID) + id := new(platform.ID) if err := id.Decode(defID); err != nil { return 0, err } @@ -200,7 +202,7 @@ func (s *Service) isDBRPUnique(ctx context.Context, m influxdb.DBRPMappingV2) er } // FindBy returns the mapping for the given ID. -func (s *Service) FindByID(ctx context.Context, orgID, id influxdb.ID) (*influxdb.DBRPMappingV2, error) { +func (s *Service) FindByID(ctx context.Context, orgID, id platform.ID) (*influxdb.DBRPMappingV2, error) { encodedID, err := id.Encode() if err != nil { return nil, ErrInvalidDBRPID(id.String(), err) @@ -239,8 +241,8 @@ func (s *Service) FindByID(ctx context.Context, orgID, id influxdb.ID) (*influxd // TODO(affo): find a smart way to apply FindOptions to a list of items. func (s *Service) FindMany(ctx context.Context, filter influxdb.DBRPMappingFilterV2, opts ...influxdb.FindOptions) ([]*influxdb.DBRPMappingV2, int, error) { // Memoize default IDs. - defs := make(map[string]*influxdb.ID) - get := func(tx kv.Tx, orgID influxdb.ID, db string) (*influxdb.ID, error) { + defs := make(map[string]*platform.ID) + get := func(tx kv.Tx, orgID platform.ID, db string) (*platform.ID, error) { k := orgID.String() + db if _, ok := defs[k]; !ok { id, err := s.getDefaultID(tx, composeForeignKey(orgID, db)) @@ -471,7 +473,7 @@ func (s *Service) Update(ctx context.Context, dbrp *influxdb.DBRPMappingV2) erro // Delete removes a mapping. // Deleting a mapping that does not exists is not an error. // Deleting the default mapping will cause the first one (if any) to become the default. -func (s *Service) Delete(ctx context.Context, orgID, id influxdb.ID) error { +func (s *Service) Delete(ctx context.Context, orgID, id platform.ID) error { dbrp, err := s.FindByID(ctx, orgID, id) if err != nil { return nil diff --git a/dbrp/service_test.go b/dbrp/service_test.go index dc5fa4cf8be..cffe5840f2d 100644 --- a/dbrp/service_test.go +++ b/dbrp/service_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" "io/ioutil" "os" "testing" @@ -55,7 +56,7 @@ func initDBRPMappingService(f itesting.DBRPMappingFieldsV2, t *testing.T) (influ if f.BucketSvc == nil { f.BucketSvc = &mock.BucketService{ - FindBucketByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { // always find a bucket. return &influxdb.Bucket{ ID: id, diff --git a/dbrp_mapping.go b/dbrp_mapping.go index 34089da02de..e7b045d161d 100644 --- a/dbrp_mapping.go +++ b/dbrp_mapping.go @@ -5,13 +5,16 @@ import ( "strconv" "strings" "unicode" + + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) // DBRPMappingServiceV2 provides CRUD to DBRPMappingV2s. type DBRPMappingServiceV2 interface { // FindBy returns the dbrp mapping for the specified ID. // Requires orgID because every resource will be org-scoped. - FindByID(ctx context.Context, orgID, id ID) (*DBRPMappingV2, error) + FindByID(ctx context.Context, orgID, id platform.ID) (*DBRPMappingV2, error) // FindMany returns a list of dbrp mappings that match filter and the total count of matching dbrp mappings. FindMany(ctx context.Context, dbrp DBRPMappingFilterV2, opts ...FindOptions) ([]*DBRPMappingV2, int, error) // Create creates a new dbrp mapping, if a different mapping exists an error is returned. @@ -21,45 +24,45 @@ type DBRPMappingServiceV2 interface { // Delete removes a dbrp mapping. // Deleting a mapping that does not exists is not an error. // Requires orgID because every resource will be org-scoped. - Delete(ctx context.Context, orgID, id ID) error + Delete(ctx context.Context, orgID, id platform.ID) error } // DBRPMappingV2 represents a mapping of a database and retention policy to an organization ID and bucket ID. type DBRPMappingV2 struct { - ID ID `json:"id"` - Database string `json:"database"` - RetentionPolicy string `json:"retention_policy"` + ID platform.ID `json:"id"` + Database string `json:"database"` + RetentionPolicy string `json:"retention_policy"` // Default indicates if this mapping is the default for the cluster and database. Default bool `json:"default"` - OrganizationID ID `json:"orgID"` - BucketID ID `json:"bucketID"` + OrganizationID platform.ID `json:"orgID"` + BucketID platform.ID `json:"bucketID"` } // Validate reports any validation errors for the mapping. func (m DBRPMappingV2) Validate() error { if !validName(m.Database) { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "database must contain at least one character and only be letters, numbers, '_', '-', and '.'", } } if !validName(m.RetentionPolicy) { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "retentionPolicy must contain at least one character and only be letters, numbers, '_', '-', and '.'", } } if !m.OrganizationID.Valid() { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "organizationID is required", } } if !m.BucketID.Valid() { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "bucketID is required", } } @@ -89,9 +92,9 @@ func (m *DBRPMappingV2) Equal(o *DBRPMappingV2) bool { // DBRPMappingFilterV2 represents a set of filters that restrict the returned results. type DBRPMappingFilterV2 struct { - ID *ID - OrgID *ID - BucketID *ID + ID *platform.ID + OrgID *platform.ID + BucketID *platform.ID Database *string RetentionPolicy *string @@ -170,39 +173,39 @@ type DBRPMapping struct { // Default indicates if this mapping is the default for the cluster and database. Default bool `json:"default"` - OrganizationID ID `json:"organization_id"` - BucketID ID `json:"bucket_id"` + OrganizationID platform.ID `json:"organization_id"` + BucketID platform.ID `json:"bucket_id"` } // Validate reports any validation errors for the mapping. func (m DBRPMapping) Validate() error { if !validName(m.Cluster) { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "cluster must contain at least one character and only be letters, numbers, '_', '-', and '.'", } } if !validName(m.Database) { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "database must contain at least one character and only be letters, numbers, '_', '-', and '.'", } } if !validName(m.RetentionPolicy) { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "retentionPolicy must contain at least one character and only be letters, numbers, '_', '-', and '.'", } } if !m.OrganizationID.Valid() { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "organizationID is required", } } if !m.BucketID.Valid() { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "bucketID is required", } } diff --git a/dbrp_mapping_test.go b/dbrp_mapping_test.go index ccf19db3edf..a5a882a1a4b 100644 --- a/dbrp_mapping_test.go +++ b/dbrp_mapping_test.go @@ -1,6 +1,7 @@ package influxdb_test import ( + platform2 "github.com/influxdata/influxdb/v2/kit/platform" "testing" platform "github.com/influxdata/influxdb/v2" @@ -13,8 +14,8 @@ func TestDBRPMapping_Validate(t *testing.T) { Database string RetentionPolicy string Default bool - OrganizationID platform.ID - BucketID platform.ID + OrganizationID platform2.ID + BucketID platform2.ID } tests := []struct { name string diff --git a/delete.go b/delete.go index 983c595e7c5..68bfc258087 100644 --- a/delete.go +++ b/delete.go @@ -1,6 +1,10 @@ package influxdb -import "context" +import ( + "context" + + "github.com/influxdata/influxdb/v2/kit/platform" +) // Predicate is something that can match on a series key. type Predicate interface { @@ -11,5 +15,5 @@ type Predicate interface { // DeleteService will delete a bucket from the range and predict. type DeleteService interface { - DeleteBucketRangePredicate(ctx context.Context, orgID, bucketID ID, min, max int64, pred Predicate) error + DeleteBucketRangePredicate(ctx context.Context, orgID, bucketID platform.ID, min, max int64, pred Predicate) error } diff --git a/document.go b/document.go index fa5fcca2120..989d8e682eb 100644 --- a/document.go +++ b/document.go @@ -2,6 +2,8 @@ package influxdb import ( "context" + + "github.com/influxdata/influxdb/v2/kit/platform" ) // ErrDocumentNotFound is the error msg for a missing document. @@ -15,7 +17,7 @@ type DocumentService interface { // Document is a generic structure for stating data. type Document struct { - ID ID `json:"id"` + ID platform.ID `json:"id"` Meta DocumentMeta `json:"meta"` Content interface{} `json:"content,omitempty"` // TODO(desa): maybe this needs to be json.Marshaller & json.Unmarshaler Labels []*Label `json:"labels,omitempty"` // read only @@ -25,7 +27,7 @@ type Document struct { // via request parameters or others, as the kv store will take care of // filling it once it returns a document. // This is not stored in the kv store neither required in the API. - Organizations map[ID]UserType `json:"-"` + Organizations map[platform.ID]UserType `json:"-"` } // DocumentMeta is information that is universal across documents. Ideally @@ -42,7 +44,7 @@ type DocumentMeta struct { // pattern that allows users to perform actions related to documents in a transactional way. type DocumentStore interface { CreateDocument(ctx context.Context, d *Document) error - FindDocument(ctx context.Context, id ID) (*Document, error) + FindDocument(ctx context.Context, id platform.ID) (*Document, error) - FindDocuments(ctx context.Context, orgID ID) ([]*Document, error) + FindDocuments(ctx context.Context, orgID platform.ID) ([]*Document, error) } diff --git a/gather/metrics.go b/gather/metrics.go index 6ce40072905..4735117aba2 100644 --- a/gather/metrics.go +++ b/gather/metrics.go @@ -5,15 +5,16 @@ import ( "io" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/gogo/protobuf/proto" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/models" ) // MetricsCollection is the struct including metrics and other requirements. type MetricsCollection struct { - OrgID influxdb.ID `json:"orgID"` - BucketID influxdb.ID `json:"bucketID"` + OrgID platform.ID `json:"orgID"` + BucketID platform.ID `json:"bucketID"` MetricsSlice MetricsSlice `json:"metrics"` } diff --git a/gather/scraper_test.go b/gather/scraper_test.go index a03ee26b11d..13ae273b64a 100644 --- a/gather/scraper_test.go +++ b/gather/scraper_test.go @@ -9,13 +9,15 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" ) var ( - orgID, _ = influxdb.IDFromString("020f755c3c082000") - bucketID, _ = influxdb.IDFromString("020f755c3c082001") + orgID, _ = platform.IDFromString("020f755c3c082000") + bucketID, _ = platform.IDFromString("020f755c3c082001") ) func TestPrometheusScraper(t *testing.T) { @@ -220,7 +222,7 @@ func (s *mockStorage) ListTargets(ctx context.Context, filter influxdb.ScraperTa return s.Targets, nil } -func (s *mockStorage) AddTarget(ctx context.Context, t *influxdb.ScraperTarget, userID influxdb.ID) error { +func (s *mockStorage) AddTarget(ctx context.Context, t *influxdb.ScraperTarget, userID platform.ID) error { s.Lock() defer s.Unlock() if s.Targets == nil { @@ -230,7 +232,7 @@ func (s *mockStorage) AddTarget(ctx context.Context, t *influxdb.ScraperTarget, return nil } -func (s *mockStorage) RemoveTarget(ctx context.Context, id influxdb.ID) error { +func (s *mockStorage) RemoveTarget(ctx context.Context, id platform.ID) error { s.Lock() defer s.Unlock() @@ -246,7 +248,7 @@ func (s *mockStorage) RemoveTarget(ctx context.Context, id influxdb.ID) error { return nil } -func (s *mockStorage) GetTargetByID(ctx context.Context, id influxdb.ID) (target *influxdb.ScraperTarget, err error) { +func (s *mockStorage) GetTargetByID(ctx context.Context, id platform.ID) (target *influxdb.ScraperTarget, err error) { s.RLock() defer s.RUnlock() @@ -261,7 +263,7 @@ func (s *mockStorage) GetTargetByID(ctx context.Context, id influxdb.ID) (target } -func (s *mockStorage) UpdateTarget(ctx context.Context, update *influxdb.ScraperTarget, userID influxdb.ID) (target *influxdb.ScraperTarget, err error) { +func (s *mockStorage) UpdateTarget(ctx context.Context, update *influxdb.ScraperTarget, userID platform.ID) (target *influxdb.ScraperTarget, err error) { s.Lock() defer s.Unlock() diff --git a/http/api_handler.go b/http/api_handler.go index 8588f4f3106..f493a173951 100644 --- a/http/api_handler.go +++ b/http/api_handler.go @@ -4,6 +4,9 @@ import ( "context" "net/http" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" @@ -31,7 +34,7 @@ type APIHandler struct { type APIBackend struct { AssetsPath string // if empty then assets are served from bindata. Logger *zap.Logger - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler SessionRenewDisabled bool // MaxBatchSizeBytes is the maximum number of bytes which can be written // in a single points batch @@ -261,7 +264,7 @@ var apiLinks = map[string]interface{}{ "delete": "/api/v2/delete", } -func serveLinksHandler(errorHandler influxdb.HTTPErrorHandler) http.Handler { +func serveLinksHandler(errorHandler errors.HTTPErrorHandler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() if err := encodeResponse(ctx, w, http.StatusOK, apiLinks); err != nil { @@ -271,21 +274,21 @@ func serveLinksHandler(errorHandler influxdb.HTTPErrorHandler) http.Handler { return http.HandlerFunc(fn) } -func decodeIDFromCtx(ctx context.Context, name string) (influxdb.ID, error) { +func decodeIDFromCtx(ctx context.Context, name string) (platform.ID, error) { params := httprouter.ParamsFromContext(ctx) idStr := params.ByName(name) if idStr == "" { - return 0, &influxdb.Error{ - Code: influxdb.EInvalid, + return 0, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing " + name, } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(idStr); err != nil { - return 0, &influxdb.Error{ - Code: influxdb.EInvalid, + return 0, &errors.Error{ + Code: errors.EInvalid, Err: err, } } diff --git a/http/auth_service.go b/http/auth_service.go index fed46058928..f0ea40a40bf 100644 --- a/http/auth_service.go +++ b/http/auth_service.go @@ -8,6 +8,9 @@ import ( "net/http" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" platcontext "github.com/influxdata/influxdb/v2/context" @@ -20,7 +23,7 @@ const prefixAuthorization = "/api/v2/authorizations" // AuthorizationBackend is all services and associated parameters required to construct // the AuthorizationHandler. type AuthorizationBackend struct { - influxdb.HTTPErrorHandler + errors2.HTTPErrorHandler log *zap.Logger AuthorizationService influxdb.AuthorizationService @@ -45,7 +48,7 @@ func NewAuthorizationBackend(log *zap.Logger, b *APIBackend) *AuthorizationBacke // AuthorizationHandler represents an HTTP API handler for authorizations. type AuthorizationHandler struct { *httprouter.Router - influxdb.HTTPErrorHandler + errors2.HTTPErrorHandler log *zap.Logger OrganizationService influxdb.OrganizationService @@ -76,13 +79,13 @@ func NewAuthorizationHandler(log *zap.Logger, b *AuthorizationBackend) *Authoriz } type authResponse struct { - ID influxdb.ID `json:"id"` + ID platform.ID `json:"id"` Token string `json:"token"` Status influxdb.Status `json:"status"` Description string `json:"description"` - OrgID influxdb.ID `json:"orgID"` + OrgID platform.ID `json:"orgID"` Org string `json:"org"` - UserID influxdb.ID `json:"userID"` + UserID platform.ID `json:"userID"` User string `json:"user"` Permissions []permissionResponse `json:"permissions"` Links map[string]string `json:"links"` @@ -153,7 +156,7 @@ func newPermissionsResponse(ctx context.Context, ps []influxdb.Permission, svc i if p.Resource.ID != nil { name, err := svc.FindResourceName(ctx, p.Resource.Type, *p.Resource.ID) - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors2.ErrorCode(err) == errors2.ENotFound { continue } if err != nil { @@ -164,7 +167,7 @@ func newPermissionsResponse(ctx context.Context, ps []influxdb.Permission, svc i if p.Resource.OrgID != nil { name, err := svc.FindResourceName(ctx, influxdb.OrgsResourceType, *p.Resource.OrgID) - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors2.ErrorCode(err) == errors2.ENotFound { continue } if err != nil { @@ -241,13 +244,13 @@ func (h *AuthorizationHandler) handlePostAuthorization(w http.ResponseWriter, r type postAuthorizationRequest struct { Status influxdb.Status `json:"status"` - OrgID influxdb.ID `json:"orgID"` - UserID *influxdb.ID `json:"userID,omitempty"` + OrgID platform.ID `json:"orgID"` + UserID *platform.ID `json:"userID,omitempty"` Description string `json:"description"` Permissions []influxdb.Permission `json:"permissions"` } -func (p *postAuthorizationRequest) toPlatform(userID influxdb.ID) *influxdb.Authorization { +func (p *postAuthorizationRequest) toPlatform(userID platform.ID) *influxdb.Authorization { return &influxdb.Authorization{ OrgID: p.OrgID, Status: p.Status, @@ -282,24 +285,24 @@ func (p *postAuthorizationRequest) SetDefaults() { func (p *postAuthorizationRequest) Validate() error { if len(p.Permissions) == 0 { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors2.Error{ + Code: errors2.EInvalid, Msg: "authorization must include permissions", } } for _, perm := range p.Permissions { if err := perm.Valid(); err != nil { - return &influxdb.Error{ + return &errors2.Error{ Err: err, } } } if !p.OrgID.Valid() { - return &influxdb.Error{ - Err: influxdb.ErrInvalidID, - Code: influxdb.EInvalid, + return &errors2.Error{ + Err: platform.ErrInvalidID, + Code: errors2.EInvalid, Msg: "org id required", } } @@ -319,8 +322,8 @@ func (p *postAuthorizationRequest) Validate() error { func decodePostAuthorizationRequest(ctx context.Context, r *http.Request) (*postAuthorizationRequest, error) { a := &postAuthorizationRequest{} if err := json.NewDecoder(r.Body).Decode(a); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: "invalid json structure", Err: err, } @@ -390,7 +393,7 @@ func decodeGetAuthorizationsRequest(ctx context.Context, r *http.Request) (*getA userID := qp.Get("userID") if userID != "" { - id, err := influxdb.IDFromString(userID) + id, err := platform.IDFromString(userID) if err != nil { return nil, err } @@ -404,7 +407,7 @@ func decodeGetAuthorizationsRequest(ctx context.Context, r *http.Request) (*getA orgID := qp.Get("orgID") if orgID != "" { - id, err := influxdb.IDFromString(orgID) + id, err := platform.IDFromString(orgID) if err != nil { return nil, err } @@ -418,7 +421,7 @@ func decodeGetAuthorizationsRequest(ctx context.Context, r *http.Request) (*getA authID := qp.Get("id") if authID != "" { - id, err := influxdb.IDFromString(authID) + id, err := platform.IDFromString(authID) if err != nil { return nil, err } @@ -472,20 +475,20 @@ func (h *AuthorizationHandler) handleGetAuthorization(w http.ResponseWriter, r * } type getAuthorizationRequest struct { - ID influxdb.ID + ID platform.ID } func decodeGetAuthorizationRequest(ctx context.Context, r *http.Request) (*getAuthorizationRequest, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -543,7 +546,7 @@ func (h *AuthorizationHandler) handleUpdateAuthorization(w http.ResponseWriter, } type updateAuthorizationRequest struct { - ID influxdb.ID + ID platform.ID *influxdb.AuthorizationUpdate } @@ -551,13 +554,13 @@ func decodeUpdateAuthorizationRequest(ctx context.Context, r *http.Request) (*up params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -595,20 +598,20 @@ func (h *AuthorizationHandler) handleDeleteAuthorization(w http.ResponseWriter, } type deleteAuthorizationRequest struct { - ID influxdb.ID + ID platform.ID } func decodeDeleteAuthorizationRequest(ctx context.Context, r *http.Request) (*deleteAuthorizationRequest, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -637,7 +640,7 @@ type AuthorizationService struct { var _ influxdb.AuthorizationService = (*AuthorizationService)(nil) // FindAuthorizationByID finds the authorization against a remote influx server. -func (s *AuthorizationService) FindAuthorizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) { +func (s *AuthorizationService) FindAuthorizationByID(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) { var b influxdb.Authorization err := s.Client. Get(prefixAuthorization, id.String()). @@ -706,7 +709,7 @@ func (s *AuthorizationService) CreateAuthorization(ctx context.Context, a *influ } // UpdateAuthorization updates the status and description if available. -func (s *AuthorizationService) UpdateAuthorization(ctx context.Context, id influxdb.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { +func (s *AuthorizationService) UpdateAuthorization(ctx context.Context, id platform.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { var res authResponse err := s.Client. PatchJSON(upd, prefixAuthorization, id.String()). @@ -720,7 +723,7 @@ func (s *AuthorizationService) UpdateAuthorization(ctx context.Context, id influ } // DeleteAuthorization removes a authorization by id. -func (s *AuthorizationService) DeleteAuthorization(ctx context.Context, id influxdb.ID) error { +func (s *AuthorizationService) DeleteAuthorization(ctx context.Context, id platform.ID) error { return s.Client. Delete(prefixAuthorization, id.String()). Do(ctx) diff --git a/http/auth_test.go b/http/auth_test.go index 4b53a99f272..4b14c1cf190 100644 --- a/http/auth_test.go +++ b/http/auth_test.go @@ -10,6 +10,9 @@ import ( "net/http/httptest" "testing" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" platform "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/authorization" @@ -83,7 +86,7 @@ func TestService_handleGetAuthorizations(t *testing.T) { }, }, &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id platform.ID) (*platform.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform2.ID) (*platform.User, error) { return &platform.User{ ID: id, Name: id.String(), @@ -91,7 +94,7 @@ func TestService_handleGetAuthorizations(t *testing.T) { }, }, &mock.OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*platform.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform2.ID) (*platform.Organization, error) { return &platform.Organization{ ID: id, Name: id.String(), @@ -176,18 +179,18 @@ func TestService_handleGetAuthorizations(t *testing.T) { }, }, &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id platform.ID) (*platform.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform2.ID) (*platform.User, error) { if id.String() == "2070616e656d2076" { return &platform.User{ ID: id, Name: id.String(), }, nil } - return nil, &platform.Error{} + return nil, &errors.Error{} }, }, &mock.OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*platform.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform2.ID) (*platform.Organization, error) { return &platform.Organization{ ID: id, Name: id.String(), @@ -254,7 +257,7 @@ func TestService_handleGetAuthorizations(t *testing.T) { }, }, &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id platform.ID) (*platform.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform2.ID) (*platform.User, error) { return &platform.User{ ID: id, Name: id.String(), @@ -262,14 +265,14 @@ func TestService_handleGetAuthorizations(t *testing.T) { }, }, &mock.OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*platform.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform2.ID) (*platform.Organization, error) { if id.String() == "3070616e656d2076" { return &platform.Organization{ ID: id, Name: id.String(), }, nil } - return nil, &platform.Error{} + return nil, &errors.Error{} }, }, }, @@ -399,7 +402,7 @@ func TestService_handleGetAuthorization(t *testing.T) { name: "get a authorization by id", fields: fields{ AuthorizationService: &mock.AuthorizationService{ - FindAuthorizationByIDFn: func(ctx context.Context, id platform.ID) (*platform.Authorization, error) { + FindAuthorizationByIDFn: func(ctx context.Context, id platform2.ID) (*platform.Authorization, error) { if id == platformtesting.MustIDBase16("020f755c3c082000") { return &platform.Authorization{ ID: platformtesting.MustIDBase16("020f755c3c082000"), @@ -411,7 +414,7 @@ func TestService_handleGetAuthorization(t *testing.T) { Resource: platform.Resource{ Type: platform.BucketsResourceType, OrgID: platformtesting.IDPtr(platformtesting.MustIDBase16("020f755c3c083000")), - ID: func() *platform.ID { + ID: func() *platform2.ID { id := platformtesting.MustIDBase16("020f755c3c084000") return &id }(), @@ -426,7 +429,7 @@ func TestService_handleGetAuthorization(t *testing.T) { }, }, UserService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id platform.ID) (*platform.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform2.ID) (*platform.User, error) { return &platform.User{ ID: id, Name: "u1", @@ -434,7 +437,7 @@ func TestService_handleGetAuthorization(t *testing.T) { }, }, OrganizationService: &mock.OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*platform.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform2.ID) (*platform.Organization, error) { return &platform.Organization{ ID: id, Name: "o1", @@ -442,7 +445,7 @@ func TestService_handleGetAuthorization(t *testing.T) { }, }, LookupService: &mock.LookupService{ - NameFn: func(ctx context.Context, resource platform.ResourceType, id platform.ID) (string, error) { + NameFn: func(ctx context.Context, resource platform.ResourceType, id platform2.ID) (string, error) { switch resource { case platform.BucketsResourceType: return "b1", nil @@ -495,9 +498,9 @@ func TestService_handleGetAuthorization(t *testing.T) { name: "not found", fields: fields{ AuthorizationService: &mock.AuthorizationService{ - FindAuthorizationByIDFn: func(ctx context.Context, id platform.ID) (*platform.Authorization, error) { - return nil, &platform.Error{ - Code: platform.ENotFound, + FindAuthorizationByIDFn: func(ctx context.Context, id platform2.ID) (*platform.Authorization, error) { + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: "authorization not found", } }, @@ -595,7 +598,7 @@ func TestService_handlePostAuthorization(t *testing.T) { }, }, LookupService: &mock.LookupService{ - NameFn: func(ctx context.Context, resource platform.ResourceType, id platform.ID) (string, error) { + NameFn: func(ctx context.Context, resource platform.ResourceType, id platform2.ID) (string, error) { switch resource { case platform.BucketsResourceType: return "b1", nil @@ -606,9 +609,9 @@ func TestService_handlePostAuthorization(t *testing.T) { }, }, UserService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id platform.ID) (*platform.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform2.ID) (*platform.User, error) { if !id.Valid() { - return nil, platform.ErrInvalidID + return nil, platform2.ErrInvalidID } return &platform.User{ ID: id, @@ -617,9 +620,9 @@ func TestService_handlePostAuthorization(t *testing.T) { }, }, OrganizationService: &mock.OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*platform.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform2.ID) (*platform.Organization, error) { if !id.Valid() { - return nil, platform.ErrInvalidID + return nil, platform2.ErrInvalidID } return &platform.Organization{ ID: id, @@ -767,7 +770,7 @@ func TestService_handleDeleteAuthorization(t *testing.T) { name: "remove a authorization by id", fields: fields{ &mock.AuthorizationService{ - DeleteAuthorizationFn: func(ctx context.Context, id platform.ID) error { + DeleteAuthorizationFn: func(ctx context.Context, id platform2.ID) error { if id == platformtesting.MustIDBase16("020f755c3c082000") { return nil } @@ -789,9 +792,9 @@ func TestService_handleDeleteAuthorization(t *testing.T) { name: "authorization not found", fields: fields{ &mock.AuthorizationService{ - DeleteAuthorizationFn: func(ctx context.Context, id platform.ID) error { - return &platform.Error{ - Code: platform.ENotFound, + DeleteAuthorizationFn: func(ctx context.Context, id platform2.ID) error { + return &errors.Error{ + Code: errors.ENotFound, Msg: "authorization not found", } }, @@ -911,7 +914,7 @@ func initAuthorizationService(f platformtesting.AuthorizationFields, t *testing. } mus := &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id platform.ID) (*platform.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform2.ID) (*platform.User, error) { return &platform.User{}, nil }, } @@ -922,7 +925,7 @@ func initAuthorizationService(f platformtesting.AuthorizationFields, t *testing. authorizationBackend.UserService = mus authorizationBackend.OrganizationService = tenantService authorizationBackend.LookupService = &mock.LookupService{ - NameFn: func(ctx context.Context, resource platform.ResourceType, id platform.ID) (string, error) { + NameFn: func(ctx context.Context, resource platform.ResourceType, id platform2.ID) (string, error) { switch resource { case platform.BucketsResourceType: return "b1", nil diff --git a/http/authentication_middleware.go b/http/authentication_middleware.go index 01c1b1cc00c..6bdb3aacf78 100644 --- a/http/authentication_middleware.go +++ b/http/authentication_middleware.go @@ -7,6 +7,8 @@ import ( "net/http" "time" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" platform "github.com/influxdata/influxdb/v2" platcontext "github.com/influxdata/influxdb/v2/context" @@ -17,7 +19,7 @@ import ( // AuthenticationHandler is a middleware for authenticating incoming requests. type AuthenticationHandler struct { - platform.HTTPErrorHandler + errors2.HTTPErrorHandler log *zap.Logger AuthorizationService platform.AuthorizationService @@ -34,7 +36,7 @@ type AuthenticationHandler struct { } // NewAuthenticationHandler creates an authentication handler. -func NewAuthenticationHandler(log *zap.Logger, h platform.HTTPErrorHandler) *AuthenticationHandler { +func NewAuthenticationHandler(log *zap.Logger, h errors2.HTTPErrorHandler) *AuthenticationHandler { return &AuthenticationHandler{ log: log, HTTPErrorHandler: h, @@ -135,7 +137,7 @@ func (h *AuthenticationHandler) isUserActive(ctx context.Context, auth platform. return nil } - return &platform.Error{Code: platform.EForbidden, Msg: "User is inactive"} + return &errors2.Error{Code: errors2.EForbidden, Msg: "User is inactive"} } func (h *AuthenticationHandler) extractAuthorization(ctx context.Context, r *http.Request) (platform.Authorizer, error) { diff --git a/http/authentication_test.go b/http/authentication_test.go index d008d8e2bbd..c6c83f6a08a 100644 --- a/http/authentication_test.go +++ b/http/authentication_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" "net/http" "net/http/httptest" "testing" @@ -19,7 +20,7 @@ import ( const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJjbG91ZDIuaW5mbHV4ZGF0YS5jb20iLCJhdWQiOiJnYXRld2F5LmluZmx1eGRhdGEuY29tIiwiaWF0IjoxNTY4NjI4OTgwLCJraWQiOiJzb21lLWtleSIsInBlcm1pc3Npb25zIjpbeyJhY3Rpb24iOiJ3cml0ZSIsInJlc291cmNlIjp7InR5cGUiOiJidWNrZXRzIiwiaWQiOiIwMDAwMDAwMDAwMDAwMDAxIiwib3JnSUQiOiIwMDAwMDAwMDAwMDAwMDAyIn19XX0.74vjbExiOd702VSIMmQWaDT_GFvUI0-_P-SfQ_OOHB0" -var one = influxdb.ID(1) +var one = platform.ID(1) func TestAuthenticationHandler(t *testing.T) { type fields struct { @@ -123,7 +124,7 @@ func TestAuthenticationHandler(t *testing.T) { }, SessionService: mock.NewSessionService(), UserService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { if !id.Valid() { panic("user service should only be called with valid user ID") } @@ -160,7 +161,7 @@ func TestAuthenticationHandler(t *testing.T) { }, SessionService: mock.NewSessionService(), UserService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { // ensure that this is not reached as jwt token authorizer produces // invalid user id if !id.Valid() { @@ -213,7 +214,7 @@ func TestAuthenticationHandler(t *testing.T) { h.AuthorizationService = tt.fields.AuthorizationService h.SessionService = tt.fields.SessionService h.UserService = &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{}, nil }, } diff --git a/http/backup_service.go b/http/backup_service.go index 00ae9f7d444..74599a329cc 100644 --- a/http/backup_service.go +++ b/http/backup_service.go @@ -9,6 +9,8 @@ import ( "strconv" "time" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/tracing" @@ -18,7 +20,7 @@ import ( // BackupBackend is all services and associated parameters required to construct the BackupHandler. type BackupBackend struct { Logger *zap.Logger - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler BackupService influxdb.BackupService } @@ -36,7 +38,7 @@ func NewBackupBackend(b *APIBackend) *BackupBackend { // BackupHandler is http handler for backup service. type BackupHandler struct { *httprouter.Router - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler Logger *zap.Logger BackupService influxdb.BackupService diff --git a/http/check_service.go b/http/check_service.go index d8fce78a2cd..be9ccffafd7 100644 --- a/http/check_service.go +++ b/http/check_service.go @@ -9,6 +9,9 @@ import ( "path" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" pctx "github.com/influxdata/influxdb/v2/context" @@ -21,7 +24,7 @@ import ( // CheckBackend is all services and associated parameters required to construct // the CheckBackendHandler. type CheckBackend struct { - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger AlgoWProxy FeatureProxyHandler @@ -53,7 +56,7 @@ func NewCheckBackend(log *zap.Logger, b *APIBackend) *CheckBackend { // CheckHandler is the handler for the check service type CheckHandler struct { *httprouter.Router - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger TaskService influxdb.TaskService @@ -254,12 +257,12 @@ func (h *CheckHandler) newChecksResponse(ctx context.Context, chks []influxdb.Ch return resp } -func decodeGetCheckRequest(ctx context.Context, r *http.Request) (i influxdb.ID, err error) { +func decodeGetCheckRequest(ctx context.Context, r *http.Request) (i platform.ID, err error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return i, &influxdb.Error{ - Code: influxdb.EInvalid, + return i, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } @@ -376,10 +379,10 @@ func decodeCheckFilter(ctx context.Context, r *http.Request) (*influxdb.CheckFil q := r.URL.Query() if orgIDStr := q.Get("orgID"); orgIDStr != "" { - orgID, err := influxdb.IDFromString(orgIDStr) + orgID, err := platform.IDFromString(orgIDStr) if err != nil { - return f, opts, &influxdb.Error{ - Code: influxdb.EInvalid, + return f, opts, &errors.Error{ + Code: errors.EInvalid, Msg: "orgID is invalid", Err: err, } @@ -398,8 +401,8 @@ type decodeStatus struct { func decodePostCheckRequest(r *http.Request) (postCheckRequest, error) { b, err := ioutil.ReadAll(r.Body) if err != nil { - return postCheckRequest{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return postCheckRequest{}, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -407,24 +410,24 @@ func decodePostCheckRequest(r *http.Request) (postCheckRequest, error) { chk, err := check.UnmarshalJSON(b) if err != nil { - return postCheckRequest{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return postCheckRequest{}, &errors.Error{ + Code: errors.EInvalid, Err: err, } } var ds decodeStatus if err := json.Unmarshal(b, &ds); err != nil { - return postCheckRequest{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return postCheckRequest{}, &errors.Error{ + Code: errors.EInvalid, Err: err, } } var dl decodeLabels if err := json.Unmarshal(b, &dl); err != nil { - return postCheckRequest{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return postCheckRequest{}, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -442,24 +445,24 @@ func decodePutCheckRequest(ctx context.Context, lang influxdb.FluxLanguageServic params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return influxdb.CheckCreate{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return influxdb.CheckCreate{}, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - i := new(influxdb.ID) + i := new(platform.ID) if err := i.DecodeFromString(id); err != nil { - return influxdb.CheckCreate{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return influxdb.CheckCreate{}, &errors.Error{ + Code: errors.EInvalid, Msg: "invalid check id format", } } b, err := ioutil.ReadAll(r.Body) if err != nil { - return influxdb.CheckCreate{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return influxdb.CheckCreate{}, &errors.Error{ + Code: errors.EInvalid, Msg: "unable to read HTTP body", Err: err, } @@ -468,8 +471,8 @@ func decodePutCheckRequest(ctx context.Context, lang influxdb.FluxLanguageServic chk, err := check.UnmarshalJSON(b) if err != nil { - return influxdb.CheckCreate{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return influxdb.CheckCreate{}, &errors.Error{ + Code: errors.EInvalid, Msg: "malformed check body", Err: err, } @@ -483,8 +486,8 @@ func decodePutCheckRequest(ctx context.Context, lang influxdb.FluxLanguageServic var ds decodeStatus err = json.Unmarshal(b, &ds) if err != nil { - return influxdb.CheckCreate{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return influxdb.CheckCreate{}, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -496,34 +499,34 @@ func decodePutCheckRequest(ctx context.Context, lang influxdb.FluxLanguageServic } type patchCheckRequest struct { - influxdb.ID + platform.ID Update influxdb.CheckUpdate } func decodePatchCheckRequest(ctx context.Context, r *http.Request) (*patchCheckRequest, error) { id := httprouter.ParamsFromContext(ctx).ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } var upd influxdb.CheckUpdate if err := json.NewDecoder(r.Body).Decode(&upd); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: err.Error(), } } if err := upd.Valid(); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: err.Error(), } } @@ -574,7 +577,7 @@ func (h *CheckHandler) handlePostCheck(w http.ResponseWriter, r *http.Request) { func (h *CheckHandler) mapNewCheckLabels(ctx context.Context, chk influxdb.CheckCreate, labels []string) []*influxdb.Label { var ls []*influxdb.Label for _, sid := range labels { - var lid influxdb.ID + var lid platform.ID err := lid.DecodeFromString(sid) if err != nil { @@ -689,7 +692,7 @@ func (h *CheckHandler) handleDeleteCheck(w http.ResponseWriter, r *http.Request) w.WriteHeader(http.StatusNoContent) } -func checkIDPath(id influxdb.ID) string { +func checkIDPath(id platform.ID) string { return path.Join(prefixChecks, id.String()) } @@ -701,7 +704,7 @@ type CheckService struct { } // FindCheckByID returns the Check matching the ID. -func (s *CheckService) FindCheckByID(ctx context.Context, id influxdb.ID) (*Check, error) { +func (s *CheckService) FindCheckByID(ctx context.Context, id platform.ID) (*Check, error) { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -728,14 +731,14 @@ func (s *CheckService) FindCheck(ctx context.Context, filter influxdb.CheckFilte } if n == 0 && filter.Name != nil { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindBucket, Msg: fmt.Sprintf("check %q not found", *filter.Name), } } else if n == 0 { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindBucket, Msg: "check not found", } @@ -795,7 +798,7 @@ func (s *CheckService) CreateCheck(ctx context.Context, c *Check) (*Check, error } // UpdateCheck updates a check. -func (s *CheckService) UpdateCheck(ctx context.Context, id influxdb.ID, u *Check) (*Check, error) { +func (s *CheckService) UpdateCheck(ctx context.Context, id platform.ID, u *Check) (*Check, error) { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -812,7 +815,7 @@ func (s *CheckService) UpdateCheck(ctx context.Context, id influxdb.ID, u *Check } // PatchCheck changes the status, description or name of a check. -func (s *CheckService) PatchCheck(ctx context.Context, id influxdb.ID, u influxdb.CheckUpdate) (*Check, error) { +func (s *CheckService) PatchCheck(ctx context.Context, id platform.ID, u influxdb.CheckUpdate) (*Check, error) { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -829,7 +832,7 @@ func (s *CheckService) PatchCheck(ctx context.Context, id influxdb.ID, u influxd } // DeleteCheck removes a check. -func (s *CheckService) DeleteCheck(ctx context.Context, id influxdb.ID) error { +func (s *CheckService) DeleteCheck(ctx context.Context, id platform.ID) error { return s.Client. Delete(checkIDPath(id)). Do(ctx) @@ -843,10 +846,10 @@ type Checks struct { } type Check struct { - ID influxdb.ID `json:"id,omitempty"` + ID platform.ID `json:"id,omitempty"` Name string `json:"name"` - OrgID influxdb.ID `json:"orgID,omitempty"` - OwnerID influxdb.ID `json:"ownerID,omitempty"` + OrgID platform.ID `json:"orgID,omitempty"` + OwnerID platform.ID `json:"ownerID,omitempty"` CreatedAt time.Time `json:"createdAt,omitempty"` UpdatedAt time.Time `json:"updatedAt,omitempty"` Query *CheckQuery `json:"query"` diff --git a/http/check_test.go b/http/check_test.go index 1bf0556f329..8cd5674cb26 100644 --- a/http/check_test.go +++ b/http/check_test.go @@ -11,6 +11,9 @@ import ( "path" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/flux/parser" "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" @@ -281,7 +284,7 @@ func TestService_handleGetChecks(t *testing.T) { checkBackend.CheckService = tt.fields.CheckService checkBackend.LabelService = tt.fields.LabelService checkBackend.TaskService = &mock.TaskService{ - FindTaskByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + FindTaskByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { return &influxdb.Task{Status: "active"}, nil }, } @@ -353,7 +356,7 @@ func TestService_handleGetCheckQuery(t *testing.T) { name: "get a check query by id", fields: fields{ &mock.CheckService{ - FindCheckByIDFn: func(ctx context.Context, id influxdb.ID) (influxdb.Check, error) { + FindCheckByIDFn: func(ctx context.Context, id platform.ID) (influxdb.Check, error) { if id == influxTesting.MustIDBase16("020f755c3c082000") { return &check.Threshold{ Base: check.Base{ @@ -423,7 +426,7 @@ func TestService_handleGetCheckQuery(t *testing.T) { checkBackend.HTTPErrorHandler = kithttp.ErrorHandler(0) checkBackend.CheckService = tt.fields.CheckService checkBackend.TaskService = &mock.TaskService{ - FindTaskByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + FindTaskByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { return &influxdb.Task{}, nil }, } @@ -471,7 +474,7 @@ func TestService_handleGetCheck(t *testing.T) { name: "get a check by id", fields: fields{ &mock.CheckService{ - FindCheckByIDFn: func(ctx context.Context, id influxdb.ID) (influxdb.Check, error) { + FindCheckByIDFn: func(ctx context.Context, id platform.ID) (influxdb.Check, error) { if id == influxTesting.MustIDBase16("020f755c3c082000") { return &check.Deadman{ Base: check.Base{ @@ -541,9 +544,9 @@ func TestService_handleGetCheck(t *testing.T) { name: "not found", fields: fields{ &mock.CheckService{ - FindCheckByIDFn: func(ctx context.Context, id influxdb.ID) (influxdb.Check, error) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + FindCheckByIDFn: func(ctx context.Context, id platform.ID) (influxdb.Check, error) { + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: "check not found", } }, @@ -564,7 +567,7 @@ func TestService_handleGetCheck(t *testing.T) { checkBackend.HTTPErrorHandler = kithttp.ErrorHandler(0) checkBackend.CheckService = tt.fields.CheckService checkBackend.TaskService = &mock.TaskService{ - FindTaskByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + FindTaskByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { return &influxdb.Task{Status: "active"}, nil }, } @@ -614,7 +617,7 @@ func TestService_handlePostCheck(t *testing.T) { OrganizationService influxdb.OrganizationService } type args struct { - userID influxdb.ID + userID platform.ID check influxdb.Check } type wants struct { @@ -633,7 +636,7 @@ func TestService_handlePostCheck(t *testing.T) { name: "create a new check", fields: fields{ CheckService: &mock.CheckService{ - CreateCheckFn: func(ctx context.Context, c influxdb.CheckCreate, userID influxdb.ID) error { + CreateCheckFn: func(ctx context.Context, c influxdb.CheckCreate, userID platform.ID) error { c.SetID(influxTesting.MustIDBase16("020f755c3c082000")) c.SetOwnerID(userID) return nil @@ -731,7 +734,7 @@ func TestService_handlePostCheck(t *testing.T) { checkBackend.CheckService = tt.fields.CheckService checkBackend.OrganizationService = tt.fields.OrganizationService checkBackend.TaskService = &mock.TaskService{ - FindTaskByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + FindTaskByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { return &influxdb.Task{Status: "active"}, nil }, } @@ -791,7 +794,7 @@ func TestService_handleDeleteCheck(t *testing.T) { name: "remove a check by id", fields: fields{ &mock.CheckService{ - DeleteCheckFn: func(ctx context.Context, id influxdb.ID) error { + DeleteCheckFn: func(ctx context.Context, id platform.ID) error { if id == influxTesting.MustIDBase16("020f755c3c082000") { return nil } @@ -811,9 +814,9 @@ func TestService_handleDeleteCheck(t *testing.T) { name: "check not found", fields: fields{ &mock.CheckService{ - DeleteCheckFn: func(ctx context.Context, id influxdb.ID) error { - return &influxdb.Error{ - Code: influxdb.ENotFound, + DeleteCheckFn: func(ctx context.Context, id platform.ID) error { + return &errors.Error{ + Code: errors.ENotFound, Msg: "check not found", } }, @@ -834,7 +837,7 @@ func TestService_handleDeleteCheck(t *testing.T) { checkBackend.HTTPErrorHandler = kithttp.ErrorHandler(0) checkBackend.CheckService = tt.fields.CheckService checkBackend.TaskService = &mock.TaskService{ - FindTaskByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + FindTaskByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { return &influxdb.Task{}, nil }, } @@ -901,7 +904,7 @@ func TestService_handlePatchCheck(t *testing.T) { name: "update a check name", fields: fields{ &mock.CheckService{ - PatchCheckFn: func(ctx context.Context, id influxdb.ID, upd influxdb.CheckUpdate) (influxdb.Check, error) { + PatchCheckFn: func(ctx context.Context, id platform.ID, upd influxdb.CheckUpdate) (influxdb.Check, error) { if id == influxTesting.MustIDBase16("020f755c3c082000") { d := &check.Deadman{ Base: check.Base{ @@ -976,9 +979,9 @@ func TestService_handlePatchCheck(t *testing.T) { name: "check not found", fields: fields{ &mock.CheckService{ - PatchCheckFn: func(ctx context.Context, id influxdb.ID, upd influxdb.CheckUpdate) (influxdb.Check, error) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + PatchCheckFn: func(ctx context.Context, id platform.ID, upd influxdb.CheckUpdate) (influxdb.Check, error) { + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: "check not found", } }, @@ -1000,7 +1003,7 @@ func TestService_handlePatchCheck(t *testing.T) { checkBackend.HTTPErrorHandler = kithttp.ErrorHandler(0) checkBackend.CheckService = tt.fields.CheckService checkBackend.TaskService = &mock.TaskService{ - FindTaskByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + FindTaskByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { return &influxdb.Task{Status: "active"}, nil }, } @@ -1077,7 +1080,7 @@ func TestService_handleUpdateCheck(t *testing.T) { name: "update a check name", fields: fields{ CheckService: &mock.CheckService{ - UpdateCheckFn: func(ctx context.Context, id influxdb.ID, chk influxdb.CheckCreate) (influxdb.Check, error) { + UpdateCheckFn: func(ctx context.Context, id platform.ID, chk influxdb.CheckCreate) (influxdb.Check, error) { if id == influxTesting.MustIDBase16("020f755c3c082000") { d := &check.Deadman{ Base: check.Base{ @@ -1163,9 +1166,9 @@ func TestService_handleUpdateCheck(t *testing.T) { name: "check not found", fields: fields{ CheckService: &mock.CheckService{ - UpdateCheckFn: func(ctx context.Context, id influxdb.ID, chk influxdb.CheckCreate) (influxdb.Check, error) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + UpdateCheckFn: func(ctx context.Context, id platform.ID, chk influxdb.CheckCreate) (influxdb.Check, error) { + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: "check not found", } }, @@ -1194,7 +1197,7 @@ func TestService_handleUpdateCheck(t *testing.T) { checkBackend.HTTPErrorHandler = kithttp.ErrorHandler(0) checkBackend.CheckService = tt.fields.CheckService checkBackend.TaskService = &mock.TaskService{ - FindTaskByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + FindTaskByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { return &influxdb.Task{Status: "active"}, nil }, } @@ -1266,7 +1269,7 @@ func TestService_handlePostCheckMember(t *testing.T) { name: "add a check member", fields: fields{ UserService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ ID: id, Name: "name", @@ -1305,7 +1308,7 @@ func TestService_handlePostCheckMember(t *testing.T) { checkBackend := NewMockCheckBackend(t) checkBackend.UserService = tt.fields.UserService checkBackend.TaskService = &mock.TaskService{ - FindTaskByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + FindTaskByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { return &influxdb.Task{}, nil }, } @@ -1365,7 +1368,7 @@ func TestService_handlePostCheckOwner(t *testing.T) { name: "add a check owner", fields: fields{ UserService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ ID: id, Name: "name", diff --git a/http/chronograf_handler.go b/http/chronograf_handler.go index e66a676d8d4..f1dd3a666ab 100644 --- a/http/chronograf_handler.go +++ b/http/chronograf_handler.go @@ -2,8 +2,8 @@ package http import ( "github.com/influxdata/httprouter" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/chronograf/server" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) const prefixChronograf = "/chronograf" @@ -15,7 +15,7 @@ type ChronografHandler struct { } // NewChronografHandler is the constructor an chronograf handler. -func NewChronografHandler(s *server.Service, he influxdb.HTTPErrorHandler) *ChronografHandler { +func NewChronografHandler(s *server.Service, he errors.HTTPErrorHandler) *ChronografHandler { h := &ChronografHandler{ Router: NewRouter(he), Service: s, diff --git a/http/delete_handler.go b/http/delete_handler.go index 13cd048daf4..528466f8411 100644 --- a/http/delete_handler.go +++ b/http/delete_handler.go @@ -8,6 +8,8 @@ import ( http "net/http" "time" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" pcontext "github.com/influxdata/influxdb/v2/context" @@ -20,7 +22,7 @@ import ( // the DeleteHandler. type DeleteBackend struct { log *zap.Logger - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler DeleteService influxdb.DeleteService BucketService influxdb.BucketService @@ -41,7 +43,7 @@ func NewDeleteBackend(log *zap.Logger, b *APIBackend) *DeleteBackend { // DeleteHandler receives a delete request with a predicate and sends it to storage. type DeleteHandler struct { - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler *httprouter.Router log *zap.Logger @@ -96,8 +98,8 @@ func (h *DeleteHandler) handleDelete(w http.ResponseWriter, r *http.Request) { p, err := influxdb.NewPermissionAtID(dr.Bucket.ID, influxdb.WriteAction, influxdb.BucketsResourceType, dr.Org.ID) if err != nil { - h.HandleHTTPError(ctx, &influxdb.Error{ - Code: influxdb.EInternal, + h.HandleHTTPError(ctx, &errors.Error{ + Code: errors.EInternal, Op: "http/handleDelete", Msg: fmt.Sprintf("unable to create permission for bucket: %v", err), Err: err, @@ -106,8 +108,8 @@ func (h *DeleteHandler) handleDelete(w http.ResponseWriter, r *http.Request) { } if pset, err := a.PermissionSet(); err != nil || !pset.Allowed(*p) { - h.HandleHTTPError(ctx, &influxdb.Error{ - Code: influxdb.EForbidden, + h.HandleHTTPError(ctx, &errors.Error{ + Code: errors.EForbidden, Op: "http/handleDelete", Msg: "insufficient permissions to delete", }, w) @@ -115,8 +117,8 @@ func (h *DeleteHandler) handleDelete(w http.ResponseWriter, r *http.Request) { } if err := h.DeleteService.DeleteBucketRangePredicate(r.Context(), dr.Org.ID, dr.Bucket.ID, dr.Start, dr.Stop, dr.Predicate); err != nil { - h.HandleHTTPError(ctx, &influxdb.Error{ - Code: influxdb.EInternal, + h.HandleHTTPError(ctx, &errors.Error{ + Code: errors.EInternal, Op: "http/handleDelete", Msg: fmt.Sprintf("unable to delete: %v", err), Err: err, @@ -136,8 +138,8 @@ func decodeDeleteRequest(ctx context.Context, r *http.Request, orgSvc influxdb.O dr := new(deleteRequest) err := json.NewDecoder(r.Body).Decode(dr) if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "invalid request; error parsing request json", Err: err, } @@ -180,8 +182,8 @@ type DeleteRequest struct { func (dr *deleteRequest) UnmarshalJSON(b []byte) error { var drd deleteRequestDecode if err := json.Unmarshal(b, &drd); err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Invalid delete predicate node request", Err: err, } @@ -189,8 +191,8 @@ func (dr *deleteRequest) UnmarshalJSON(b []byte) error { *dr = deleteRequest{} start, err := time.Parse(time.RFC3339Nano, drd.Start) if err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Op: "http/Delete", Msg: "invalid RFC3339Nano for field start, please format your time with RFC3339Nano format, example: 2009-01-02T23:00:00Z", } @@ -199,8 +201,8 @@ func (dr *deleteRequest) UnmarshalJSON(b []byte) error { stop, err := time.Parse(time.RFC3339Nano, drd.Stop) if err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Op: "http/Delete", Msg: "invalid RFC3339Nano for field stop, please format your time with RFC3339Nano format, example: 2009-01-01T23:00:00Z", } diff --git a/http/delete_test.go b/http/delete_test.go index fcd3b27e985..6e4d4af0a00 100644 --- a/http/delete_test.go +++ b/http/delete_test.go @@ -8,6 +8,9 @@ import ( "net/http/httptest" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" pcontext "github.com/influxdata/influxdb/v2/context" kithttp "github.com/influxdata/influxdb/v2/kit/transport/http" @@ -98,8 +101,8 @@ func TestDelete(t *testing.T) { fields: fields{ OrganizationService: &mock.OrganizationService{ FindOrganizationF: func(ctx context.Context, f influxdb.OrganizationFilter) (*influxdb.Organization, error) { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "Please provide either orgID or org", } }, @@ -126,8 +129,8 @@ func TestDelete(t *testing.T) { fields: fields{ BucketService: &mock.BucketService{ FindBucketFn: func(ctx context.Context, f influxdb.BucketFilter) (*influxdb.Bucket, error) { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "Please provide either bucketID or bucket", } }, @@ -135,7 +138,7 @@ func TestDelete(t *testing.T) { OrganizationService: &mock.OrganizationService{ FindOrganizationF: func(ctx context.Context, f influxdb.OrganizationFilter) (*influxdb.Organization, error) { return &influxdb.Organization{ - ID: influxdb.ID(1), + ID: platform.ID(1), }, nil }, }, @@ -163,7 +166,7 @@ func TestDelete(t *testing.T) { BucketService: &mock.BucketService{ FindBucketFn: func(ctx context.Context, f influxdb.BucketFilter) (*influxdb.Bucket, error) { return &influxdb.Bucket{ - ID: influxdb.ID(2), + ID: platform.ID(2), Name: "bucket1", }, nil }, @@ -171,7 +174,7 @@ func TestDelete(t *testing.T) { OrganizationService: &mock.OrganizationService{ FindOrganizationF: func(ctx context.Context, f influxdb.OrganizationFilter) (*influxdb.Organization, error) { return &influxdb.Organization{ - ID: influxdb.ID(1), + ID: platform.ID(1), }, nil }, }, @@ -201,8 +204,8 @@ func TestDelete(t *testing.T) { Action: influxdb.WriteAction, Resource: influxdb.Resource{ Type: influxdb.BucketsResourceType, - ID: influxtesting.IDPtr(influxdb.ID(2)), - OrgID: influxtesting.IDPtr(influxdb.ID(1)), + ID: influxtesting.IDPtr(platform.ID(2)), + OrgID: influxtesting.IDPtr(platform.ID(1)), }, }, }, @@ -213,7 +216,7 @@ func TestDelete(t *testing.T) { BucketService: &mock.BucketService{ FindBucketFn: func(ctx context.Context, f influxdb.BucketFilter) (*influxdb.Bucket, error) { return &influxdb.Bucket{ - ID: influxdb.ID(2), + ID: platform.ID(2), Name: "bucket1", }, nil }, @@ -221,7 +224,7 @@ func TestDelete(t *testing.T) { OrganizationService: &mock.OrganizationService{ FindOrganizationF: func(ctx context.Context, f influxdb.OrganizationFilter) (*influxdb.Organization, error) { return &influxdb.Organization{ - ID: influxdb.ID(1), + ID: platform.ID(1), Name: "org1", }, nil }, @@ -252,8 +255,8 @@ func TestDelete(t *testing.T) { Action: influxdb.WriteAction, Resource: influxdb.Resource{ Type: influxdb.BucketsResourceType, - ID: influxtesting.IDPtr(influxdb.ID(2)), - OrgID: influxtesting.IDPtr(influxdb.ID(1)), + ID: influxtesting.IDPtr(platform.ID(2)), + OrgID: influxtesting.IDPtr(platform.ID(1)), }, }, }, @@ -264,7 +267,7 @@ func TestDelete(t *testing.T) { BucketService: &mock.BucketService{ FindBucketFn: func(ctx context.Context, f influxdb.BucketFilter) (*influxdb.Bucket, error) { return &influxdb.Bucket{ - ID: influxdb.ID(2), + ID: platform.ID(2), Name: "bucket1", }, nil }, @@ -272,7 +275,7 @@ func TestDelete(t *testing.T) { OrganizationService: &mock.OrganizationService{ FindOrganizationF: func(ctx context.Context, f influxdb.OrganizationFilter) (*influxdb.Organization, error) { return &influxdb.Organization{ - ID: influxdb.ID(1), + ID: platform.ID(1), Name: "org1", }, nil }, @@ -306,8 +309,8 @@ func TestDelete(t *testing.T) { Action: influxdb.WriteAction, Resource: influxdb.Resource{ Type: influxdb.BucketsResourceType, - ID: influxtesting.IDPtr(influxdb.ID(2)), - OrgID: influxtesting.IDPtr(influxdb.ID(1)), + ID: influxtesting.IDPtr(platform.ID(2)), + OrgID: influxtesting.IDPtr(platform.ID(1)), }, }, }, @@ -318,7 +321,7 @@ func TestDelete(t *testing.T) { BucketService: &mock.BucketService{ FindBucketFn: func(ctx context.Context, f influxdb.BucketFilter) (*influxdb.Bucket, error) { return &influxdb.Bucket{ - ID: influxdb.ID(2), + ID: platform.ID(2), Name: "bucket1", }, nil }, @@ -326,7 +329,7 @@ func TestDelete(t *testing.T) { OrganizationService: &mock.OrganizationService{ FindOrganizationF: func(ctx context.Context, f influxdb.OrganizationFilter) (*influxdb.Organization, error) { return &influxdb.Organization{ - ID: influxdb.ID(1), + ID: platform.ID(1), Name: "org1", }, nil }, diff --git a/http/document_service.go b/http/document_service.go index 0980e4404e8..a454239681e 100644 --- a/http/document_service.go +++ b/http/document_service.go @@ -6,6 +6,9 @@ import ( "net/http" "path" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/tracing" @@ -17,14 +20,14 @@ const prefixDocuments = "/api/v2/documents" // DocumentService is an interface HTTP-exposed portion of the document service. type DocumentService interface { - GetDocuments(ctx context.Context, namespace string, orgID influxdb.ID) ([]*influxdb.Document, error) + GetDocuments(ctx context.Context, namespace string, orgID platform.ID) ([]*influxdb.Document, error) } // DocumentBackend is all services and associated parameters required to construct // the DocumentHandler. type DocumentBackend struct { log *zap.Logger - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler DocumentService influxdb.DocumentService } @@ -43,7 +46,7 @@ type DocumentHandler struct { *httprouter.Router log *zap.Logger - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler DocumentService influxdb.DocumentService LabelService influxdb.LabelService @@ -133,15 +136,15 @@ func (h *DocumentHandler) handleGetDocuments(w http.ResponseWriter, r *http.Requ type getDocumentsRequest struct { Namespace string Org string - OrgID influxdb.ID + OrgID platform.ID } func decodeGetDocumentsRequest(ctx context.Context, r *http.Request) (*getDocumentsRequest, error) { params := httprouter.ParamsFromContext(ctx) ns := params.ByName("ns") if ns == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing namespace", } } @@ -153,10 +156,10 @@ func decodeGetDocumentsRequest(ctx context.Context, r *http.Request) (*getDocume } if oidStr := qp.Get("orgID"); oidStr != "" { - oid, err := influxdb.IDFromString(oidStr) + oid, err := platform.IDFromString(oidStr) if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "Invalid orgID", } } @@ -182,7 +185,7 @@ func buildDocumentsPath(namespace string) string { // GetDocuments returns the documents for a `namespace` and an `orgID`. // Returned documents do not contain their content. -func (s *documentService) GetDocuments(ctx context.Context, namespace string, orgID influxdb.ID) ([]*influxdb.Document, error) { +func (s *documentService) GetDocuments(ctx context.Context, namespace string, orgID platform.ID) ([]*influxdb.Document, error) { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() diff --git a/http/document_test.go b/http/document_test.go index b3eedf3ef8a..44ca9e61be9 100644 --- a/http/document_test.go +++ b/http/document_test.go @@ -7,6 +7,8 @@ import ( "net/http/httptest" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" pcontext "github.com/influxdata/influxdb/v2/context" @@ -73,7 +75,7 @@ var ( findDocsServiceMock = &mock.DocumentService{ FindDocumentStoreFn: func(context.Context, string) (influxdb.DocumentStore, error) { return &mock.DocumentStore{ - FindDocumentsFn: func(ctx context.Context, _ influxdb.ID) ([]*influxdb.Document, error) { + FindDocumentsFn: func(ctx context.Context, _ platform.ID) ([]*influxdb.Document, error) { return docs, nil }, }, nil @@ -96,7 +98,7 @@ func TestService_handleGetDocuments(t *testing.T) { } type args struct { authorizer influxdb.Authorizer - orgID influxdb.ID + orgID platform.ID } type wants struct { statusCode int @@ -117,7 +119,7 @@ func TestService_handleGetDocuments(t *testing.T) { }, args: args{ authorizer: mock.NewMockAuthorizer(true, nil), - orgID: influxdb.ID(2), + orgID: platform.ID(2), }, wants: wants{ statusCode: http.StatusOK, diff --git a/http/duration.go b/http/duration.go index d04171e4191..ae56628b15e 100644 --- a/http/duration.go +++ b/http/duration.go @@ -5,12 +5,12 @@ import ( "strconv" "time" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) // ErrInvalidDuration is returned when parsing a malformatted duration. -var ErrInvalidDuration = &influxdb.Error{ - Code: influxdb.EInvalid, +var ErrInvalidDuration = &errors.Error{ + Code: errors.EInvalid, Msg: "invalid duration", } diff --git a/http/errors.go b/http/errors.go index 7f4d42034e2..5b9a7f93a26 100644 --- a/http/errors.go +++ b/http/errors.go @@ -11,7 +11,8 @@ import ( "net/http" "strings" - platform "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + khttp "github.com/influxdata/influxdb/v2/kit/transport/http" ) @@ -52,13 +53,13 @@ func CheckError(resp *http.Response) (err error) { return nil default: // TODO(jsternberg): Figure out what to do here? - return &platform.Error{ - Code: platform.EInternal, + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("unexpected status code: %d %s", resp.StatusCode, resp.Status), } } - perr := &platform.Error{ + perr := &errors.Error{ Code: khttp.StatusCodeToErrorCode(resp.StatusCode), } @@ -105,17 +106,17 @@ func firstLineAsError(buf bytes.Buffer) error { } // UnauthorizedError encodes a error message and status code for unauthorized access. -func UnauthorizedError(ctx context.Context, h platform.HTTPErrorHandler, w http.ResponseWriter) { - h.HandleHTTPError(ctx, &platform.Error{ - Code: platform.EUnauthorized, +func UnauthorizedError(ctx context.Context, h errors.HTTPErrorHandler, w http.ResponseWriter) { + h.HandleHTTPError(ctx, &errors.Error{ + Code: errors.EUnauthorized, Msg: "unauthorized access", }, w) } // InactiveUserError encode a error message and status code for inactive users. -func InactiveUserError(ctx context.Context, h platform.HTTPErrorHandler, w http.ResponseWriter) { - h.HandleHTTPError(ctx, &platform.Error{ - Code: platform.EForbidden, +func InactiveUserError(ctx context.Context, h errors.HTTPErrorHandler, w http.ResponseWriter) { + h.HandleHTTPError(ctx, &errors.Error{ + Code: errors.EForbidden, Msg: "User is inactive", }, w) } diff --git a/http/errors_test.go b/http/errors_test.go index 1110bfa9883..85dc24f3ba6 100644 --- a/http/errors_test.go +++ b/http/errors_test.go @@ -4,12 +4,12 @@ import ( "context" "encoding/json" stderrors "errors" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "io" "net/http/httptest" "testing" "github.com/google/go-cmp/cmp" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/http" kithttp "github.com/influxdata/influxdb/v2/kit/transport/http" ) @@ -24,15 +24,15 @@ func TestCheckError(t *testing.T) { name: "platform error", write: func(w *httptest.ResponseRecorder) { h := kithttp.ErrorHandler(0) - err := &influxdb.Error{ + err := &errors.Error{ Msg: "expected", - Code: influxdb.EInvalid, + Code: errors.EInvalid, } h.HandleHTTPError(context.Background(), err, w) }, - want: &influxdb.Error{ + want: &errors.Error{ Msg: "expected", - Code: influxdb.EInvalid, + Code: errors.EInvalid, }, }, { @@ -42,8 +42,8 @@ func TestCheckError(t *testing.T) { w.WriteHeader(500) _, _ = io.WriteString(w, "upstream timeout\n") }, - want: &influxdb.Error{ - Code: influxdb.EInternal, + want: &errors.Error{ + Code: errors.EInternal, Err: stderrors.New("upstream timeout"), }, }, @@ -54,8 +54,8 @@ func TestCheckError(t *testing.T) { w.WriteHeader(500) _, _ = io.WriteString(w, "upstream timeout\n") }, - want: &influxdb.Error{ - Code: influxdb.EInternal, + want: &errors.Error{ + Code: errors.EInternal, Msg: `attempted to unmarshal error as JSON but failed: "invalid character 'u' looking for beginning of value"`, Err: stderrors.New("upstream timeout"), }, @@ -66,8 +66,8 @@ func TestCheckError(t *testing.T) { w.WriteHeader(500) _, _ = io.WriteString(w, `{"error": "service unavailable", "code": "unavailable"}`) }, - want: &influxdb.Error{ - Code: influxdb.EUnavailable, + want: &errors.Error{ + Code: errors.EUnavailable, Err: stderrors.New("service unavailable"), }, }, @@ -77,8 +77,8 @@ func TestCheckError(t *testing.T) { w.WriteHeader(503) _, _ = io.WriteString(w, `{"error": "service unavailable"}`) }, - want: &influxdb.Error{ - Code: influxdb.EUnavailable, + want: &errors.Error{ + Code: errors.EUnavailable, Err: stderrors.New("service unavailable"), }, }, @@ -87,8 +87,8 @@ func TestCheckError(t *testing.T) { write: func(w *httptest.ResponseRecorder) { w.WriteHeader(503) }, - want: &influxdb.Error{ - Code: influxdb.EUnavailable, + want: &errors.Error{ + Code: errors.EUnavailable, Msg: `attempted to unmarshal error as JSON but failed: "unexpected end of JSON input"`, Err: stderrors.New(""), }, @@ -100,7 +100,7 @@ func TestCheckError(t *testing.T) { resp := w.Result() cmpopt := cmp.Transformer("error", func(e error) string { - if e, ok := e.(*influxdb.Error); ok { + if e, ok := e.(*errors.Error); ok { out, _ := json.Marshal(e) return string(out) } diff --git a/http/handler.go b/http/handler.go index 6fd280e9849..7e34fbea718 100644 --- a/http/handler.go +++ b/http/handler.go @@ -5,8 +5,9 @@ import ( "encoding/json" "net/http" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/prom" kithttp "github.com/influxdata/influxdb/v2/kit/transport/http" "github.com/influxdata/influxdb/v2/pprof" @@ -60,7 +61,7 @@ func (o *handlerOpts) metricsHTTPHandler() http.Handler { return o.metricsRegistry.HTTPHandler() } handlerFunc := func(rw http.ResponseWriter, r *http.Request) { - kithttp.WriteErrorResponse(r.Context(), rw, influxdb.EForbidden, "metrics disabled") + kithttp.WriteErrorResponse(r.Context(), rw, errors.EForbidden, "metrics disabled") } return http.HandlerFunc(handlerFunc) } diff --git a/http/influxdb/bucket.go b/http/influxdb/bucket.go index 5e63c59cdfd..3507dcf8ef7 100644 --- a/http/influxdb/bucket.go +++ b/http/influxdb/bucket.go @@ -5,6 +5,8 @@ import ( "fmt" "time" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/tracing" ) @@ -14,11 +16,11 @@ type BucketService struct { Source *platform.Source } -func (s *BucketService) FindBucketByName(ctx context.Context, orgID platform.ID, n string) (*platform.Bucket, error) { +func (s *BucketService) FindBucketByName(ctx context.Context, orgID platform2.ID, n string) (*platform.Bucket, error) { return nil, fmt.Errorf("not supported") } -func (s *BucketService) FindBucketByID(ctx context.Context, id platform.ID) (*platform.Bucket, error) { +func (s *BucketService) FindBucketByID(ctx context.Context, id platform2.ID) (*platform.Bucket, error) { return nil, fmt.Errorf("not supported") } @@ -69,10 +71,10 @@ func (s *BucketService) CreateBucket(ctx context.Context, b *platform.Bucket) er return fmt.Errorf("not supported") } -func (s *BucketService) UpdateBucket(ctx context.Context, id platform.ID, upd platform.BucketUpdate) (*platform.Bucket, error) { +func (s *BucketService) UpdateBucket(ctx context.Context, id platform2.ID, upd platform.BucketUpdate) (*platform.Bucket, error) { return nil, fmt.Errorf("not supported") } -func (s *BucketService) DeleteBucket(ctx context.Context, id platform.ID) error { +func (s *BucketService) DeleteBucket(ctx context.Context, id platform2.ID) error { return fmt.Errorf("not supported") } diff --git a/http/influxdb/source_proxy_query_service.go b/http/influxdb/source_proxy_query_service.go index 0513a8656ae..5effa701e4a 100644 --- a/http/influxdb/source_proxy_query_service.go +++ b/http/influxdb/source_proxy_query_service.go @@ -8,6 +8,8 @@ import ( "io" "net/http" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/flux" "github.com/influxdata/flux/csv" "github.com/influxdata/flux/lang" @@ -22,7 +24,7 @@ import ( type SourceProxyQueryService struct { InsecureSkipVerify bool URL string - OrganizationID platform.ID + OrganizationID platform2.ID platform.SourceFields platform.V1SourceFields } diff --git a/http/label_service.go b/http/label_service.go index b8f7e4d98ec..da54454e1e8 100644 --- a/http/label_service.go +++ b/http/label_service.go @@ -8,6 +8,9 @@ import ( "net/url" "path" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/pkg/httpc" @@ -17,7 +20,7 @@ import ( // LabelHandler represents an HTTP API handler for labels type LabelHandler struct { *httprouter.Router - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger LabelService influxdb.LabelService @@ -29,7 +32,7 @@ const ( ) // NewLabelHandler returns a new instance of LabelHandler -func NewLabelHandler(log *zap.Logger, s influxdb.LabelService, he influxdb.HTTPErrorHandler) *LabelHandler { +func NewLabelHandler(log *zap.Logger, s influxdb.LabelService, he errors.HTTPErrorHandler) *LabelHandler { h := &LabelHandler{ Router: NewRouter(he), HTTPErrorHandler: he, @@ -77,14 +80,14 @@ type postLabelRequest struct { func (b postLabelRequest) Validate() error { if b.Label.Name == "" { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "label requires a name", } } if !b.Label.OrgID.Valid() { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "label requires a valid orgID", } } @@ -95,8 +98,8 @@ func (b postLabelRequest) Validate() error { func decodePostLabelRequest(ctx context.Context, r *http.Request) (*postLabelRequest, error) { l := &influxdb.Label{} if err := json.NewDecoder(r.Body).Decode(l); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unable to decode label request", Err: err, } @@ -143,7 +146,7 @@ func decodeGetLabelsRequest(qp url.Values) (*getLabelsRequest, error) { } if orgID := qp.Get("orgID"); orgID != "" { - id, err := influxdb.IDFromString(orgID) + id, err := platform.IDFromString(orgID) if err != nil { return nil, err } @@ -175,20 +178,20 @@ func (h *LabelHandler) handleGetLabel(w http.ResponseWriter, r *http.Request) { } type getLabelRequest struct { - LabelID influxdb.ID + LabelID platform.ID } func decodeGetLabelRequest(ctx context.Context, r *http.Request) (*getLabelRequest, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "label id is not valid", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -217,20 +220,20 @@ func (h *LabelHandler) handleDeleteLabel(w http.ResponseWriter, r *http.Request) } type deleteLabelRequest struct { - LabelID influxdb.ID + LabelID platform.ID } func decodeDeleteLabelRequest(ctx context.Context, r *http.Request) (*deleteLabelRequest, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -264,20 +267,20 @@ func (h *LabelHandler) handlePatchLabel(w http.ResponseWriter, r *http.Request) type patchLabelRequest struct { Update influxdb.LabelUpdate - LabelID influxdb.ID + LabelID platform.ID } func decodePatchLabelRequest(ctx context.Context, r *http.Request) (*patchLabelRequest, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -325,7 +328,7 @@ func newLabelsResponse(ls []*influxdb.Label) *labelsResponse { // label handlers. type LabelBackend struct { log *zap.Logger - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler LabelService influxdb.LabelService ResourceType influxdb.ResourceType } @@ -364,13 +367,13 @@ func decodeGetLabelMappingsRequest(ctx context.Context, rt influxdb.ResourceType params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -422,21 +425,21 @@ func decodePostLabelMappingRequest(ctx context.Context, r *http.Request, rt infl params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var rid influxdb.ID + var rid platform.ID if err := rid.DecodeFromString(id); err != nil { return nil, err } mapping := &influxdb.LabelMapping{} if err := json.NewDecoder(r.Body).Decode(mapping); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "Invalid post label map request", } } @@ -482,34 +485,34 @@ func newDeleteLabelHandler(b *LabelBackend) http.HandlerFunc { } type deleteLabelMappingRequest struct { - ResourceID influxdb.ID - LabelID influxdb.ID + ResourceID platform.ID + LabelID platform.ID } func decodeDeleteLabelMappingRequest(ctx context.Context, r *http.Request) (*deleteLabelMappingRequest, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing resource id", } } - var rid influxdb.ID + var rid platform.ID if err := rid.DecodeFromString(id); err != nil { return nil, err } id = params.ByName("lid") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "label id is missing", } } - var lid influxdb.ID + var lid platform.ID if err := lid.DecodeFromString(id); err != nil { return nil, err } @@ -520,7 +523,7 @@ func decodeDeleteLabelMappingRequest(ctx context.Context, r *http.Request) (*del }, nil } -func labelIDPath(id influxdb.ID) string { +func labelIDPath(id platform.ID) string { return path.Join(prefixLabels, id.String()) } @@ -531,7 +534,7 @@ type LabelService struct { } // FindLabelByID returns a single label by ID. -func (s *LabelService) FindLabelByID(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { +func (s *LabelService) FindLabelByID(ctx context.Context, id platform.ID) (*influxdb.Label, error) { var lr labelResponse err := s.Client. Get(labelIDPath(id)). @@ -599,7 +602,7 @@ func (s *LabelService) CreateLabel(ctx context.Context, l *influxdb.Label) error } // UpdateLabel updates a label and returns the updated label. -func (s *LabelService) UpdateLabel(ctx context.Context, id influxdb.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { +func (s *LabelService) UpdateLabel(ctx context.Context, id platform.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { var lr labelResponse err := s.Client. PatchJSON(upd, labelIDPath(id)). @@ -612,7 +615,7 @@ func (s *LabelService) UpdateLabel(ctx context.Context, id influxdb.ID, upd infl } // DeleteLabel removes a label by ID. -func (s *LabelService) DeleteLabel(ctx context.Context, id influxdb.ID) error { +func (s *LabelService) DeleteLabel(ctx context.Context, id platform.ID) error { return s.Client. Delete(labelIDPath(id)). Do(ctx) @@ -641,6 +644,6 @@ func (s *LabelService) DeleteLabelMapping(ctx context.Context, m *influxdb.Label Do(ctx) } -func resourceIDMappingPath(resourceType influxdb.ResourceType, resourceID influxdb.ID, p string, labelID influxdb.ID) string { +func resourceIDMappingPath(resourceType influxdb.ResourceType, resourceID platform.ID, p string, labelID platform.ID) string { return path.Join("/api/v2/", string(resourceType), resourceID.String(), p, labelID.String()) } diff --git a/http/label_test.go b/http/label_test.go index d3aa1943f8a..d917ebb98ed 100644 --- a/http/label_test.go +++ b/http/label_test.go @@ -10,6 +10,9 @@ import ( "net/http/httptest" "testing" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" platform "github.com/influxdata/influxdb/v2" kithttp "github.com/influxdata/influxdb/v2/kit/transport/http" @@ -159,7 +162,7 @@ func TestService_handleGetLabel(t *testing.T) { name: "get a label by id", fields: fields{ &mock.LabelService{ - FindLabelByIDFn: func(ctx context.Context, id platform.ID) (*platform.Label, error) { + FindLabelByIDFn: func(ctx context.Context, id platform2.ID) (*platform.Label, error) { if id == platformtesting.MustIDBase16("020f755c3c082000") { return &platform.Label{ ID: platformtesting.MustIDBase16("020f755c3c082000"), @@ -200,9 +203,9 @@ func TestService_handleGetLabel(t *testing.T) { name: "not found", fields: fields{ &mock.LabelService{ - FindLabelByIDFn: func(ctx context.Context, id platform.ID) (*platform.Label, error) { - return nil, &platform.Error{ - Code: platform.ENotFound, + FindLabelByIDFn: func(ctx context.Context, id platform2.ID) (*platform.Label, error) { + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: platform.ErrLabelNotFound, } }, @@ -366,7 +369,7 @@ func TestService_handleDeleteLabel(t *testing.T) { name: "remove a label by id", fields: fields{ &mock.LabelService{ - DeleteLabelFn: func(ctx context.Context, id platform.ID) error { + DeleteLabelFn: func(ctx context.Context, id platform2.ID) error { if id == platformtesting.MustIDBase16("020f755c3c082000") { return nil } @@ -386,9 +389,9 @@ func TestService_handleDeleteLabel(t *testing.T) { name: "label not found", fields: fields{ &mock.LabelService{ - DeleteLabelFn: func(ctx context.Context, id platform.ID) error { - return &platform.Error{ - Code: platform.ENotFound, + DeleteLabelFn: func(ctx context.Context, id platform2.ID) error { + return &errors.Error{ + Code: errors.ENotFound, Msg: platform.ErrLabelNotFound, } }, @@ -468,7 +471,7 @@ func TestService_handlePatchLabel(t *testing.T) { name: "update label properties", fields: fields{ &mock.LabelService{ - UpdateLabelFn: func(ctx context.Context, id platform.ID, upd platform.LabelUpdate) (*platform.Label, error) { + UpdateLabelFn: func(ctx context.Context, id platform2.ID, upd platform.LabelUpdate) (*platform.Label, error) { if id == platformtesting.MustIDBase16("020f755c3c082000") { l := &platform.Label{ ID: platformtesting.MustIDBase16("020f755c3c082000"), @@ -522,9 +525,9 @@ func TestService_handlePatchLabel(t *testing.T) { name: "label not found", fields: fields{ &mock.LabelService{ - UpdateLabelFn: func(ctx context.Context, id platform.ID, upd platform.LabelUpdate) (*platform.Label, error) { - return nil, &platform.Error{ - Code: platform.ENotFound, + UpdateLabelFn: func(ctx context.Context, id platform2.ID, upd platform.LabelUpdate) (*platform.Label, error) { + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: platform.ErrLabelNotFound, } }, diff --git a/http/legacy/backend.go b/http/legacy/backend.go index d4ea77a8f16..33c7f61aa91 100644 --- a/http/legacy/backend.go +++ b/http/legacy/backend.go @@ -3,6 +3,8 @@ package legacy import ( http2 "net/http" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/http/metric" "github.com/influxdata/influxdb/v2/influxql" @@ -15,14 +17,14 @@ import ( // Handler is a collection of all the service handlers. type Handler struct { - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler PointsWriterHandler *WriteHandler PingHandler *PingHandler InfluxQLHandler *InfluxqlHandler } type Backend struct { - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler Logger *zap.Logger MaxBatchSizeBytes int64 diff --git a/http/legacy/common.go b/http/legacy/common.go index c5b49b25519..177fd55fd03 100644 --- a/http/legacy/common.go +++ b/http/legacy/common.go @@ -3,6 +3,8 @@ package legacy import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" pcontext "github.com/influxdata/influxdb/v2/context" ) @@ -18,8 +20,8 @@ func getAuthorization(ctx context.Context) (*influxdb.Authorization, error) { a, ok := authorizer.(*influxdb.Authorization) if !ok { - return nil, &influxdb.Error{ - Code: influxdb.EForbidden, + return nil, &errors.Error{ + Code: errors.EForbidden, Msg: "insufficient permissions; session not supported", } } diff --git a/http/legacy/influx1x_authentication_handler.go b/http/legacy/influx1x_authentication_handler.go index d1d57c8e9f4..b8792d92b52 100644 --- a/http/legacy/influx1x_authentication_handler.go +++ b/http/legacy/influx1x_authentication_handler.go @@ -7,6 +7,8 @@ import ( "net/http" "strings" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" platcontext "github.com/influxdata/influxdb/v2/context" "github.com/opentracing/opentracing-go" @@ -17,14 +19,14 @@ type Authorizer interface { } type Influx1xAuthenticationHandler struct { - influxdb.HTTPErrorHandler + errors2.HTTPErrorHandler next http.Handler auth Authorizer } // NewInflux1xAuthenticationHandler creates an authentication handler to process // InfluxDB 1.x authentication requests. -func NewInflux1xAuthenticationHandler(next http.Handler, auth Authorizer, h influxdb.HTTPErrorHandler) *Influx1xAuthenticationHandler { +func NewInflux1xAuthenticationHandler(next http.Handler, auth Authorizer, h errors2.HTTPErrorHandler) *Influx1xAuthenticationHandler { return &Influx1xAuthenticationHandler{ HTTPErrorHandler: h, next: next, @@ -49,10 +51,10 @@ func (h *Influx1xAuthenticationHandler) ServeHTTP(w http.ResponseWriter, r *http auth, err := h.auth.Authorize(ctx, creds) if err != nil { - var erri *influxdb.Error + var erri *errors2.Error if errors.As(err, &erri) { switch erri.Code { - case influxdb.EForbidden, influxdb.EUnauthorized: + case errors2.EForbidden, errors2.EUnauthorized: h.HandleHTTPError(ctx, erri, w) return } @@ -132,9 +134,9 @@ func (h *Influx1xAuthenticationHandler) parseCredentials(r *http.Request) (influ } // unauthorizedError encodes a error message and status code for unauthorized access. -func unauthorizedError(ctx context.Context, h influxdb.HTTPErrorHandler, w http.ResponseWriter) { - h.HandleHTTPError(ctx, &influxdb.Error{ - Code: influxdb.EUnauthorized, +func unauthorizedError(ctx context.Context, h errors2.HTTPErrorHandler, w http.ResponseWriter) { + h.HandleHTTPError(ctx, &errors2.Error{ + Code: errors2.EUnauthorized, Msg: "unauthorized access", }, w) } diff --git a/http/legacy/influx1x_authentication_handler_test.go b/http/legacy/influx1x_authentication_handler_test.go index 86af41be859..0202bcf31d3 100644 --- a/http/legacy/influx1x_authentication_handler_test.go +++ b/http/legacy/influx1x_authentication_handler_test.go @@ -7,6 +7,8 @@ import ( "net/http/httptest" "testing" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/golang/mock/gomock" "github.com/influxdata/influxdb/v2" kithttp "github.com/influxdata/influxdb/v2/kit/transport/http" @@ -104,7 +106,7 @@ func TestInflux1xAuthenticationHandler(t *testing.T) { name: "token does not exist", fields: fields{ AuthorizeFn: func(ctx context.Context, c influxdb.CredentialsV1) (*influxdb.Authorization, error) { - return nil, &influxdb.Error{Code: influxdb.EUnauthorized} + return nil, &errors.Error{Code: errors.EUnauthorized} }, }, exp: exp{ @@ -115,7 +117,7 @@ func TestInflux1xAuthenticationHandler(t *testing.T) { name: "authorize returns error EForbidden", fields: fields{ AuthorizeFn: func(ctx context.Context, c influxdb.CredentialsV1) (*influxdb.Authorization, error) { - return nil, &influxdb.Error{Code: influxdb.EForbidden} + return nil, &errors.Error{Code: errors.EForbidden} }, }, auth: basic(User, Token), @@ -127,7 +129,7 @@ func TestInflux1xAuthenticationHandler(t *testing.T) { name: "authorize returns error EUnauthorized", fields: fields{ AuthorizeFn: func(ctx context.Context, c influxdb.CredentialsV1) (*influxdb.Authorization, error) { - return nil, &influxdb.Error{Code: influxdb.EUnauthorized} + return nil, &errors.Error{Code: errors.EUnauthorized} }, }, auth: basic(User, Token), @@ -139,7 +141,7 @@ func TestInflux1xAuthenticationHandler(t *testing.T) { name: "authorize returns error other", fields: fields{ AuthorizeFn: func(ctx context.Context, c influxdb.CredentialsV1) (*influxdb.Authorization, error) { - return nil, &influxdb.Error{Code: influxdb.EInvalid} + return nil, &errors.Error{Code: errors.EInvalid} }, }, auth: basic(User, Token), diff --git a/http/legacy/influxql_handler.go b/http/legacy/influxql_handler.go index 0ff7248d4d7..c172a3c1269 100644 --- a/http/legacy/influxql_handler.go +++ b/http/legacy/influxql_handler.go @@ -3,6 +3,8 @@ package legacy import ( "net/http" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + platform "github.com/influxdata/influxdb/v2" influxqld "github.com/influxdata/influxdb/v2/influxql" "github.com/influxdata/influxdb/v2/influxql/control" @@ -19,7 +21,7 @@ type InfluxqlHandler struct { } type InfluxQLBackend struct { - platform.HTTPErrorHandler + errors.HTTPErrorHandler Logger *zap.Logger AuthorizationService platform.AuthorizationService OrganizationService platform.OrganizationService diff --git a/http/legacy/influxqld_handler.go b/http/legacy/influxqld_handler.go index 56a37e874d8..a3614cc8973 100644 --- a/http/legacy/influxqld_handler.go +++ b/http/legacy/influxqld_handler.go @@ -8,6 +8,8 @@ import ( "strconv" "strings" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/flux/iocounter" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/influxql" @@ -46,8 +48,8 @@ func (h *InfluxqlHandler) handleInfluxqldQuery(w http.ResponseWriter, r *http.Re } if !auth.IsActive() { - h.HandleHTTPError(ctx, &influxdb.Error{ - Code: influxdb.EForbidden, + h.HandleHTTPError(ctx, &errors.Error{ + Code: errors.EForbidden, Msg: "insufficient permissions", }, w) return @@ -79,8 +81,8 @@ func (h *InfluxqlHandler) handleInfluxqldQuery(w http.ResponseWriter, r *http.Re ct := r.Header.Get("Content-Type") mt, _, err := mime.ParseMediaType(ct) if err != nil { - h.HandleHTTPError(ctx, &influxdb.Error{ - Code: influxdb.EInvalid, + h.HandleHTTPError(ctx, &errors.Error{ + Code: errors.EInvalid, Err: err, }, w) return @@ -103,8 +105,8 @@ func (h *InfluxqlHandler) handleInfluxqldQuery(w http.ResponseWriter, r *http.Re decoder := json.NewDecoder(strings.NewReader(rawParams)) decoder.UseNumber() if err := decoder.Decode(¶ms); err != nil { - h.HandleHTTPError(ctx, &influxdb.Error{ - Code: influxdb.EInvalid, + h.HandleHTTPError(ctx, &errors.Error{ + Code: errors.EInvalid, Msg: "error parsing query parameters", Err: err, }, w) @@ -122,8 +124,8 @@ func (h *InfluxqlHandler) handleInfluxqldQuery(w http.ResponseWriter, r *http.Re } if err != nil { - h.HandleHTTPError(ctx, &influxdb.Error{ - Code: influxdb.EInvalid, + h.HandleHTTPError(ctx, &errors.Error{ + Code: errors.EInvalid, Msg: "error parsing json value", Err: err, }, w) diff --git a/http/legacy/influxqld_handler_test.go b/http/legacy/influxqld_handler_test.go index 3839850df9c..fb54ca76ce0 100644 --- a/http/legacy/influxqld_handler_test.go +++ b/http/legacy/influxqld_handler_test.go @@ -8,6 +8,8 @@ import ( "net/http/httptest" "testing" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" platform "github.com/influxdata/influxdb/v2" pcontext "github.com/influxdata/influxdb/v2/context" @@ -94,8 +96,8 @@ func TestInfluxQLdHandler_HandleQuery(t *testing.T) { fields: fields{ OrganizationService: &mock.OrganizationService{ FindOrganizationF: func(ctx context.Context, filter platform.OrganizationFilter) (*platform.Organization, error) { - return nil, &platform.Error{ - Code: platform.EForbidden, + return nil, &errors.Error{ + Code: errors.EForbidden, Msg: "nope", } }, @@ -123,8 +125,8 @@ func TestInfluxQLdHandler_HandleQuery(t *testing.T) { }, ProxyQueryService: &imock.ProxyQueryService{ QueryF: func(ctx context.Context, w io.Writer, req *influxql.QueryRequest) (influxql.Statistics, error) { - return influxql.Statistics{}, &platform.Error{ - Code: platform.EUnprocessableEntity, + return influxql.Statistics{}, &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: "bad query", } }, @@ -153,8 +155,8 @@ func TestInfluxQLdHandler_HandleQuery(t *testing.T) { ProxyQueryService: &imock.ProxyQueryService{ QueryF: func(ctx context.Context, w io.Writer, req *influxql.QueryRequest) (influxql.Statistics, error) { _, _ = io.WriteString(w, "fail") - return influxql.Statistics{}, &platform.Error{ - Code: platform.EInternal, + return influxql.Statistics{}, &errors.Error{ + Code: errors.EInternal, Msg: "during query", } }, diff --git a/http/legacy/router.go b/http/legacy/router.go index 32deff4f622..ad5045b376c 100644 --- a/http/legacy/router.go +++ b/http/legacy/router.go @@ -7,15 +7,16 @@ import ( "runtime/debug" "sync" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" - platform "github.com/influxdata/influxdb/v2" influxlogger "github.com/influxdata/influxdb/v2/logger" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) // NewRouter returns a new router with a 404 handler, a 405 handler, and a panic handler. -func NewRouter(h platform.HTTPErrorHandler) *httprouter.Router { +func NewRouter(h errors.HTTPErrorHandler) *httprouter.Router { b := baseHandler{HTTPErrorHandler: h} router := httprouter.New() router.NotFound = http.HandlerFunc(b.notFound) @@ -26,14 +27,14 @@ func NewRouter(h platform.HTTPErrorHandler) *httprouter.Router { } type baseHandler struct { - platform.HTTPErrorHandler + errors.HTTPErrorHandler } // notFound represents a 404 handler that return a JSON response. func (h baseHandler) notFound(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - pe := &platform.Error{ - Code: platform.ENotFound, + pe := &errors.Error{ + Code: errors.ENotFound, Msg: "path not found", } @@ -44,8 +45,8 @@ func (h baseHandler) notFound(w http.ResponseWriter, r *http.Request) { func (h baseHandler) methodNotAllowed(w http.ResponseWriter, r *http.Request) { ctx := r.Context() allow := w.Header().Get("Allow") - pe := &platform.Error{ - Code: platform.EMethodNotAllowed, + pe := &errors.Error{ + Code: errors.EMethodNotAllowed, Msg: fmt.Sprintf("allow: %s", allow), } @@ -56,8 +57,8 @@ func (h baseHandler) methodNotAllowed(w http.ResponseWriter, r *http.Request) { // It returns a json response with http status code 500 and the recovered error message. func (h baseHandler) panic(w http.ResponseWriter, r *http.Request, rcv interface{}) { ctx := r.Context() - pe := &platform.Error{ - Code: platform.EInternal, + pe := &errors.Error{ + Code: errors.EInternal, Msg: "a panic has occurred", Err: fmt.Errorf("%s: %v", r.URL.String(), rcv), } diff --git a/http/legacy/write_handler.go b/http/legacy/write_handler.go index fd3381ffd29..b0281f80de7 100644 --- a/http/legacy/write_handler.go +++ b/http/legacy/write_handler.go @@ -6,6 +6,9 @@ import ( "io" "net/http" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/http/metric" @@ -25,7 +28,7 @@ const ( // PointsWriterBackend contains all the services needed to run a PointsWriterHandler. type PointsWriterBackend struct { - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler Logger *zap.Logger EventRecorder metric.EventRecorder @@ -48,7 +51,7 @@ func NewPointsWriterBackend(b *Backend) *PointsWriterBackend { // PointsWriterHandler represents an HTTP API handler for writing points. type WriteHandler struct { - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler EventRecorder metric.EventRecorder BucketService influxdb.BucketService PointsWriter storage.PointsWriter @@ -143,8 +146,8 @@ func (h *WriteHandler) handleWrite(w http.ResponseWriter, r *http.Request) { if err := h.PointsWriter.WritePoints(ctx, auth.OrgID, bucket.ID, parsed.Points); err != nil { if partialErr, ok := err.(tsdb.PartialWriteError); ok { - h.HandleHTTPError(ctx, &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + h.HandleHTTPError(ctx, &errors.Error{ + Code: errors.EUnprocessableEntity, Op: opWriteHandler, Msg: "failure writing points to database", Err: partialErr, @@ -152,8 +155,8 @@ func (h *WriteHandler) handleWrite(w http.ResponseWriter, r *http.Request) { return } - h.HandleHTTPError(ctx, &influxdb.Error{ - Code: influxdb.EInternal, + h.HandleHTTPError(ctx, &errors.Error{ + Code: errors.EInternal, Op: opWriteHandler, Msg: "unexpected error writing points to database", Err: err, @@ -166,7 +169,7 @@ func (h *WriteHandler) handleWrite(w http.ResponseWriter, r *http.Request) { // findBucket finds a bucket for the specified database and // retention policy combination. -func (h *WriteHandler) findBucket(ctx context.Context, orgID influxdb.ID, db, rp string) (*influxdb.Bucket, error) { +func (h *WriteHandler) findBucket(ctx context.Context, orgID platform.ID, db, rp string) (*influxdb.Bucket, error) { mapping, err := h.findMapping(ctx, orgID, db, rp) if err != nil { return nil, err @@ -177,19 +180,19 @@ func (h *WriteHandler) findBucket(ctx context.Context, orgID influxdb.ID, db, rp // checkBucketWritePermissions checks an Authorizer for write permissions to a // specific Bucket. -func checkBucketWritePermissions(auth influxdb.Authorizer, orgID, bucketID influxdb.ID) error { +func checkBucketWritePermissions(auth influxdb.Authorizer, orgID, bucketID platform.ID) error { p, err := influxdb.NewPermissionAtID(bucketID, influxdb.WriteAction, influxdb.BucketsResourceType, orgID) if err != nil { - return &influxdb.Error{ - Code: influxdb.EInternal, + return &errors.Error{ + Code: errors.EInternal, Op: opWriteHandler, Msg: fmt.Sprintf("unable to create permission for bucket: %v", err), Err: err, } } if pset, err := auth.PermissionSet(); err != nil || !pset.Allowed(*p) { - return &influxdb.Error{ - Code: influxdb.EForbidden, + return &errors.Error{ + Code: errors.EForbidden, Op: opWriteHandler, Msg: "insufficient permissions for write", Err: err, @@ -200,7 +203,7 @@ func checkBucketWritePermissions(auth influxdb.Authorizer, orgID, bucketID influ // findMapping finds a DBRPMappingV2 for the database and retention policy // combination. -func (h *WriteHandler) findMapping(ctx context.Context, orgID influxdb.ID, db, rp string) (*influxdb.DBRPMappingV2, error) { +func (h *WriteHandler) findMapping(ctx context.Context, orgID platform.ID, db, rp string) (*influxdb.DBRPMappingV2, error) { filter := influxdb.DBRPMappingFilterV2{ OrgID: &orgID, Database: &db, @@ -217,8 +220,8 @@ func (h *WriteHandler) findMapping(ctx context.Context, orgID influxdb.ID, db, r return nil, err } if count == 0 { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: "no dbrp mapping found", } } @@ -245,8 +248,8 @@ func decodeWriteRequest(_ context.Context, r *http.Request, maxBatchSizeBytes in } db := qp.Get("db") if db == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "missing db", } } diff --git a/http/legacy/write_handler_test.go b/http/legacy/write_handler_test.go index e6c76682683..973d73642ba 100644 --- a/http/legacy/write_handler_test.go +++ b/http/legacy/write_handler_test.go @@ -11,6 +11,8 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/golang/mock/gomock" "github.com/influxdata/influxdb/v2" pcontext "github.com/influxdata/influxdb/v2/context" @@ -472,7 +474,7 @@ func (m pointsMatcher) String() string { return fmt.Sprintf("%#v", m.points) } -func newPermissions(action influxdb.Action, resourceType influxdb.ResourceType, orgID, id *influxdb.ID) []influxdb.Permission { +func newPermissions(action influxdb.Action, resourceType influxdb.ResourceType, orgID, id *platform.ID) []influxdb.Permission { return []influxdb.Permission{ { Action: action, @@ -485,7 +487,7 @@ func newPermissions(action influxdb.Action, resourceType influxdb.ResourceType, } } -func newAuthorization(orgID influxdb.ID, permissions ...influxdb.Permission) *influxdb.Authorization { +func newAuthorization(orgID platform.ID, permissions ...influxdb.Permission) *influxdb.Authorization { return &influxdb.Authorization{ ID: generator.ID(), Status: influxdb.Active, diff --git a/http/legacy/write_usage_recorder.go b/http/legacy/write_usage_recorder.go index 47f34709650..cd296a3ced4 100644 --- a/http/legacy/write_usage_recorder.go +++ b/http/legacy/write_usage_recorder.go @@ -3,7 +3,8 @@ package legacy import ( "context" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/http/metric" kithttp "github.com/influxdata/influxdb/v2/kit/transport/http" ) @@ -20,7 +21,7 @@ type writeUsageRecorder struct { EventRecorder metric.EventRecorder } -func (w *writeUsageRecorder) Record(ctx context.Context, requestBytes int, orgID influxdb.ID, endpoint string) { +func (w *writeUsageRecorder) Record(ctx context.Context, requestBytes int, orgID platform.ID, endpoint string) { w.EventRecorder.Record(ctx, metric.Event{ OrgID: orgID, Endpoint: endpoint, diff --git a/http/metric/recorder.go b/http/metric/recorder.go index 39f4fedf0e1..1e6ab2f8236 100644 --- a/http/metric/recorder.go +++ b/http/metric/recorder.go @@ -3,7 +3,7 @@ package metric import ( "context" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" ) // EventRecorder records meta-data associated with http requests. @@ -13,7 +13,7 @@ type EventRecorder interface { // Event represents the meta data associated with an API request. type Event struct { - OrgID influxdb.ID + OrgID platform.ID Endpoint string RequestBytes int ResponseBytes int diff --git a/http/mocks/bucket_service.go b/http/mocks/bucket_service.go index 00fbb56becf..e8c59a54e42 100644 --- a/http/mocks/bucket_service.go +++ b/http/mocks/bucket_service.go @@ -6,6 +6,7 @@ package mocks import ( context "context" + "github.com/influxdata/influxdb/v2/kit/platform" reflect "reflect" gomock "github.com/golang/mock/gomock" @@ -50,7 +51,7 @@ func (mr *MockBucketServiceMockRecorder) CreateBucket(arg0, arg1 interface{}) *g } // DeleteBucket mocks base method -func (m *MockBucketService) DeleteBucket(arg0 context.Context, arg1 influxdb.ID) error { +func (m *MockBucketService) DeleteBucket(arg0 context.Context, arg1 platform.ID) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteBucket", arg0, arg1) ret0, _ := ret[0].(error) @@ -79,7 +80,7 @@ func (mr *MockBucketServiceMockRecorder) FindBucket(arg0, arg1 interface{}) *gom } // FindBucketByID mocks base method -func (m *MockBucketService) FindBucketByID(arg0 context.Context, arg1 influxdb.ID) (*influxdb.Bucket, error) { +func (m *MockBucketService) FindBucketByID(arg0 context.Context, arg1 platform.ID) (*influxdb.Bucket, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "FindBucketByID", arg0, arg1) ret0, _ := ret[0].(*influxdb.Bucket) @@ -94,7 +95,7 @@ func (mr *MockBucketServiceMockRecorder) FindBucketByID(arg0, arg1 interface{}) } // FindBucketByName mocks base method -func (m *MockBucketService) FindBucketByName(arg0 context.Context, arg1 influxdb.ID, arg2 string) (*influxdb.Bucket, error) { +func (m *MockBucketService) FindBucketByName(arg0 context.Context, arg1 platform.ID, arg2 string) (*influxdb.Bucket, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "FindBucketByName", arg0, arg1, arg2) ret0, _ := ret[0].(*influxdb.Bucket) @@ -130,7 +131,7 @@ func (mr *MockBucketServiceMockRecorder) FindBuckets(arg0, arg1 interface{}, arg } // UpdateBucket mocks base method -func (m *MockBucketService) UpdateBucket(arg0 context.Context, arg1 influxdb.ID, arg2 influxdb.BucketUpdate) (*influxdb.Bucket, error) { +func (m *MockBucketService) UpdateBucket(arg0 context.Context, arg1 platform.ID, arg2 influxdb.BucketUpdate) (*influxdb.Bucket, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "UpdateBucket", arg0, arg1, arg2) ret0, _ := ret[0].(*influxdb.Bucket) diff --git a/http/mocks/dbrp_mapping_service_v2.go b/http/mocks/dbrp_mapping_service_v2.go index d8986095017..07af63edb4b 100644 --- a/http/mocks/dbrp_mapping_service_v2.go +++ b/http/mocks/dbrp_mapping_service_v2.go @@ -6,6 +6,7 @@ package mocks import ( context "context" + "github.com/influxdata/influxdb/v2/kit/platform" reflect "reflect" gomock "github.com/golang/mock/gomock" @@ -50,7 +51,7 @@ func (mr *MockDBRPMappingServiceV2MockRecorder) Create(arg0, arg1 interface{}) * } // Delete mocks base method -func (m *MockDBRPMappingServiceV2) Delete(arg0 context.Context, arg1, arg2 influxdb.ID) error { +func (m *MockDBRPMappingServiceV2) Delete(arg0 context.Context, arg1, arg2 platform.ID) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Delete", arg0, arg1, arg2) ret0, _ := ret[0].(error) @@ -64,7 +65,7 @@ func (mr *MockDBRPMappingServiceV2MockRecorder) Delete(arg0, arg1, arg2 interfac } // FindByID mocks base method -func (m *MockDBRPMappingServiceV2) FindByID(arg0 context.Context, arg1, arg2 influxdb.ID) (*influxdb.DBRPMappingV2, error) { +func (m *MockDBRPMappingServiceV2) FindByID(arg0 context.Context, arg1, arg2 platform.ID) (*influxdb.DBRPMappingV2, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "FindByID", arg0, arg1, arg2) ret0, _ := ret[0].(*influxdb.DBRPMappingV2) diff --git a/http/mocks/organization_service.go b/http/mocks/organization_service.go index 0a85295dc80..2d53fca0320 100644 --- a/http/mocks/organization_service.go +++ b/http/mocks/organization_service.go @@ -6,6 +6,7 @@ package mocks import ( context "context" + "github.com/influxdata/influxdb/v2/kit/platform" reflect "reflect" gomock "github.com/golang/mock/gomock" @@ -50,7 +51,7 @@ func (mr *MockOrganizationServiceMockRecorder) CreateOrganization(arg0, arg1 int } // DeleteOrganization mocks base method -func (m *MockOrganizationService) DeleteOrganization(arg0 context.Context, arg1 influxdb.ID) error { +func (m *MockOrganizationService) DeleteOrganization(arg0 context.Context, arg1 platform.ID) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteOrganization", arg0, arg1) ret0, _ := ret[0].(error) @@ -79,7 +80,7 @@ func (mr *MockOrganizationServiceMockRecorder) FindOrganization(arg0, arg1 inter } // FindOrganizationByID mocks base method -func (m *MockOrganizationService) FindOrganizationByID(arg0 context.Context, arg1 influxdb.ID) (*influxdb.Organization, error) { +func (m *MockOrganizationService) FindOrganizationByID(arg0 context.Context, arg1 platform.ID) (*influxdb.Organization, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "FindOrganizationByID", arg0, arg1) ret0, _ := ret[0].(*influxdb.Organization) @@ -115,7 +116,7 @@ func (mr *MockOrganizationServiceMockRecorder) FindOrganizations(arg0, arg1 inte } // UpdateOrganization mocks base method -func (m *MockOrganizationService) UpdateOrganization(arg0 context.Context, arg1 influxdb.ID, arg2 influxdb.OrganizationUpdate) (*influxdb.Organization, error) { +func (m *MockOrganizationService) UpdateOrganization(arg0 context.Context, arg1 platform.ID, arg2 influxdb.OrganizationUpdate) (*influxdb.Organization, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "UpdateOrganization", arg0, arg1, arg2) ret0, _ := ret[0].(*influxdb.Organization) diff --git a/http/mocks/points_writer.go b/http/mocks/points_writer.go index 432b214012e..5132fb6ba7f 100644 --- a/http/mocks/points_writer.go +++ b/http/mocks/points_writer.go @@ -6,10 +6,10 @@ package mocks import ( context "context" + "github.com/influxdata/influxdb/v2/kit/platform" reflect "reflect" gomock "github.com/golang/mock/gomock" - influxdb "github.com/influxdata/influxdb/v2" models "github.com/influxdata/influxdb/v2/models" ) @@ -37,7 +37,7 @@ func (m *MockPointsWriter) EXPECT() *MockPointsWriterMockRecorder { } // WritePoints mocks base method -func (m *MockPointsWriter) WritePoints(arg0 context.Context, arg1, arg2 influxdb.ID, arg3 []models.Point) error { +func (m *MockPointsWriter) WritePoints(arg0 context.Context, arg1, arg2 platform.ID, arg3 []models.Point) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "WritePoints", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(error) diff --git a/http/notification_endpoint.go b/http/notification_endpoint.go index d426bb83a1d..cc6c70b0317 100644 --- a/http/notification_endpoint.go +++ b/http/notification_endpoint.go @@ -8,6 +8,9 @@ import ( "io/ioutil" "net/http" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" pctx "github.com/influxdata/influxdb/v2/context" @@ -19,7 +22,7 @@ import ( // NotificationEndpointBackend is all services and associated parameters required to construct // the NotificationEndpointBackendHandler. type NotificationEndpointBackend struct { - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger NotificationEndpointService influxdb.NotificationEndpointService @@ -47,7 +50,7 @@ func (b *NotificationEndpointBackend) Logger() *zap.Logger { // NotificationEndpointHandler is the handler for the notificationEndpoint service type NotificationEndpointHandler struct { *httprouter.Router - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger NotificationEndpointService influxdb.NotificationEndpointService @@ -197,12 +200,12 @@ func newNotificationEndpointsResponse(ctx context.Context, edps []influxdb.Notif return resp } -func decodeGetNotificationEndpointRequest(ctx context.Context) (i influxdb.ID, err error) { +func decodeGetNotificationEndpointRequest(ctx context.Context) (i platform.ID, err error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return i, &influxdb.Error{ - Code: influxdb.EInvalid, + return i, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } @@ -274,10 +277,10 @@ func decodeNotificationEndpointFilter(ctx context.Context, r *http.Request) (inf q := r.URL.Query() if orgIDStr := q.Get("orgID"); orgIDStr != "" { - orgID, err := influxdb.IDFromString(orgIDStr) + orgID, err := platform.IDFromString(orgIDStr) if err != nil { - return influxdb.NotificationEndpointFilter{}, influxdb.FindOptions{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return influxdb.NotificationEndpointFilter{}, influxdb.FindOptions{}, &errors.Error{ + Code: errors.EInvalid, Msg: "orgID is invalid", Err: err, } @@ -288,7 +291,7 @@ func decodeNotificationEndpointFilter(ctx context.Context, r *http.Request) (inf } if userID := q.Get("user"); userID != "" { - id, err := influxdb.IDFromString(userID) + id, err := platform.IDFromString(userID) if err != nil { return influxdb.NotificationEndpointFilter{}, influxdb.FindOptions{}, err } @@ -301,24 +304,24 @@ func decodeNotificationEndpointFilter(ctx context.Context, r *http.Request) (inf func decodePostNotificationEndpointRequest(r *http.Request) (postNotificationEndpointRequest, error) { b, err := ioutil.ReadAll(r.Body) if err != nil { - return postNotificationEndpointRequest{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return postNotificationEndpointRequest{}, &errors.Error{ + Code: errors.EInvalid, Err: err, } } defer r.Body.Close() edp, err := endpoint.UnmarshalJSON(b) if err != nil { - return postNotificationEndpointRequest{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return postNotificationEndpointRequest{}, &errors.Error{ + Code: errors.EInvalid, Err: err, } } var dl decodeLabels if err := json.Unmarshal(b, &dl); err != nil { - return postNotificationEndpointRequest{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return postNotificationEndpointRequest{}, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -332,8 +335,8 @@ func decodePostNotificationEndpointRequest(r *http.Request) (postNotificationEnd func decodePutNotificationEndpointRequest(ctx context.Context, r *http.Request) (influxdb.NotificationEndpoint, error) { buf := new(bytes.Buffer) if _, err := buf.ReadFrom(r.Body); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -341,14 +344,14 @@ func decodePutNotificationEndpointRequest(ctx context.Context, r *http.Request) edp, err := endpoint.UnmarshalJSON(buf.Bytes()) if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } params := httprouter.ParamsFromContext(ctx) - i, err := influxdb.IDFromString(params.ByName("id")) + i, err := platform.IDFromString(params.ByName("id")) if err != nil { return nil, err } @@ -357,13 +360,13 @@ func decodePutNotificationEndpointRequest(ctx context.Context, r *http.Request) } type patchNotificationEndpointRequest struct { - influxdb.ID + platform.ID Update influxdb.NotificationEndpointUpdate } func decodePatchNotificationEndpointRequest(ctx context.Context, r *http.Request) (patchNotificationEndpointRequest, error) { params := httprouter.ParamsFromContext(ctx) - id, err := influxdb.IDFromString(params.ByName("id")) + id, err := platform.IDFromString(params.ByName("id")) if err != nil { return patchNotificationEndpointRequest{}, err } @@ -373,14 +376,14 @@ func decodePatchNotificationEndpointRequest(ctx context.Context, r *http.Request var upd influxdb.NotificationEndpointUpdate if err := json.NewDecoder(r.Body).Decode(&upd); err != nil { - return patchNotificationEndpointRequest{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return patchNotificationEndpointRequest{}, &errors.Error{ + Code: errors.EInvalid, Msg: err.Error(), } } if err := upd.Valid(); err != nil { - return patchNotificationEndpointRequest{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return patchNotificationEndpointRequest{}, &errors.Error{ + Code: errors.EInvalid, Msg: err.Error(), } } @@ -424,7 +427,7 @@ func (h *NotificationEndpointHandler) handlePostNotificationEndpoint(w http.Resp func (h *NotificationEndpointHandler) mapNewNotificationEndpointLabels(ctx context.Context, nre influxdb.NotificationEndpoint, labels []string) []*influxdb.Label { var ls []*influxdb.Label for _, sid := range labels { - var lid influxdb.ID + var lid platform.ID err := lid.DecodeFromString(sid) if err != nil { @@ -531,7 +534,7 @@ func (h *NotificationEndpointHandler) handleDeleteNotificationEndpoint(w http.Re keys := make([]string, len(flds)) for k, fld := range flds { if fld.Key == "" { - h.HandleHTTPError(ctx, &influxdb.Error{ + h.HandleHTTPError(ctx, &errors.Error{ Op: "http/handleDeleteNotificationEndpoint", Msg: "Bad Secret Key in endpoint " + i.String(), }, w) @@ -559,7 +562,7 @@ func NewNotificationEndpointService(client *httpc.Client) *NotificationEndpointS var _ influxdb.NotificationEndpointService = (*NotificationEndpointService)(nil) // FindNotificationEndpointByID returns a single notification endpoint by ID. -func (s *NotificationEndpointService) FindNotificationEndpointByID(ctx context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { +func (s *NotificationEndpointService) FindNotificationEndpointByID(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { if !id.Valid() { return nil, fmt.Errorf("invalid ID: please provide a valid ID") } @@ -610,7 +613,7 @@ func (s *NotificationEndpointService) FindNotificationEndpoints(ctx context.Cont // CreateNotificationEndpoint creates a new notification endpoint and sets b.ID with the new identifier. // TODO(@jsteenb2): this is unsatisfactory, we have no way of grabbing the new notification endpoint without // serious hacky hackertoning. Put it on the list... -func (s *NotificationEndpointService) CreateNotificationEndpoint(ctx context.Context, ne influxdb.NotificationEndpoint, userID influxdb.ID) error { +func (s *NotificationEndpointService) CreateNotificationEndpoint(ctx context.Context, ne influxdb.NotificationEndpoint, userID platform.ID) error { var resp notificationEndpointDecoder err := s.Client. PostJSON(¬ificationEndpointEncoder{ne: ne}, prefixNotificationEndpoints). @@ -627,7 +630,7 @@ func (s *NotificationEndpointService) CreateNotificationEndpoint(ctx context.Con // UpdateNotificationEndpoint updates a single notification endpoint. // Returns the new notification endpoint after update. -func (s *NotificationEndpointService) UpdateNotificationEndpoint(ctx context.Context, id influxdb.ID, ne influxdb.NotificationEndpoint, userID influxdb.ID) (influxdb.NotificationEndpoint, error) { +func (s *NotificationEndpointService) UpdateNotificationEndpoint(ctx context.Context, id platform.ID, ne influxdb.NotificationEndpoint, userID platform.ID) (influxdb.NotificationEndpoint, error) { if !id.Valid() { return nil, fmt.Errorf("invalid ID: please provide a valid ID") } @@ -644,7 +647,7 @@ func (s *NotificationEndpointService) UpdateNotificationEndpoint(ctx context.Con // PatchNotificationEndpoint updates a single notification endpoint with changeset. // Returns the new notification endpoint state after update. -func (s *NotificationEndpointService) PatchNotificationEndpoint(ctx context.Context, id influxdb.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { +func (s *NotificationEndpointService) PatchNotificationEndpoint(ctx context.Context, id platform.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { if !id.Valid() { return nil, fmt.Errorf("invalid ID: please provide a valid ID") } @@ -668,7 +671,7 @@ func (s *NotificationEndpointService) PatchNotificationEndpoint(ctx context.Cont // I am forced to know how the store handles this and then figure out what the server does in between me and that store, // then see what falls out :flushed... for now returning nothing for secrets, orgID, and only returning an error. This makes // the code/design smell super obvious imo -func (s *NotificationEndpointService) DeleteNotificationEndpoint(ctx context.Context, id influxdb.ID) ([]influxdb.SecretField, influxdb.ID, error) { +func (s *NotificationEndpointService) DeleteNotificationEndpoint(ctx context.Context, id platform.ID) ([]influxdb.SecretField, platform.ID, error) { if !id.Valid() { return nil, 0, fmt.Errorf("invalid ID: please provide a valid ID") } diff --git a/http/notification_endpoint_test.go b/http/notification_endpoint_test.go index 181595f0244..dab3e601b6f 100644 --- a/http/notification_endpoint_test.go +++ b/http/notification_endpoint_test.go @@ -11,6 +11,9 @@ import ( "path" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" pcontext "github.com/influxdata/influxdb/v2/context" @@ -282,7 +285,7 @@ func TestService_handleGetNotificationEndpoint(t *testing.T) { name: "get a notification endpoint by id", fields: fields{ &mock.NotificationEndpointService{ - FindNotificationEndpointByIDF: func(ctx context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { + FindNotificationEndpointByIDF: func(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { if id == influxTesting.MustIDBase16("020f755c3c082000") { return &endpoint.HTTP{ Base: endpoint.Base{ @@ -340,9 +343,9 @@ func TestService_handleGetNotificationEndpoint(t *testing.T) { name: "not found", fields: fields{ &mock.NotificationEndpointService{ - FindNotificationEndpointByIDF: func(ctx context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + FindNotificationEndpointByIDF: func(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: "notification endpoint not found", } }, @@ -429,7 +432,7 @@ func TestService_handlePostNotificationEndpoint(t *testing.T) { fields: fields{ Secrets: map[string]string{}, NotificationEndpointService: &mock.NotificationEndpointService{ - CreateNotificationEndpointF: func(ctx context.Context, edp influxdb.NotificationEndpoint, userID influxdb.ID) error { + CreateNotificationEndpointF: func(ctx context.Context, edp influxdb.NotificationEndpoint, userID platform.ID) error { edp.SetID(influxTesting.MustIDBase16("020f755c3c082000")) edp.BackfillSecretKeys() return nil @@ -536,7 +539,7 @@ func TestService_handleDeleteNotificationEndpoint(t *testing.T) { name: "remove a notification endpoint by id", fields: fields{ NotificationEndpointService: &mock.NotificationEndpointService{ - DeleteNotificationEndpointF: func(ctx context.Context, id influxdb.ID) ([]influxdb.SecretField, influxdb.ID, error) { + DeleteNotificationEndpointF: func(ctx context.Context, id platform.ID) ([]influxdb.SecretField, platform.ID, error) { if id == influxTesting.MustIDBase16("020f755c3c082000") { return []influxdb.SecretField{ {Key: "k1"}, @@ -558,9 +561,9 @@ func TestService_handleDeleteNotificationEndpoint(t *testing.T) { name: "notification endpoint not found", fields: fields{ NotificationEndpointService: &mock.NotificationEndpointService{ - DeleteNotificationEndpointF: func(ctx context.Context, id influxdb.ID) ([]influxdb.SecretField, influxdb.ID, error) { - return nil, 0, &influxdb.Error{ - Code: influxdb.ENotFound, + DeleteNotificationEndpointF: func(ctx context.Context, id platform.ID) ([]influxdb.SecretField, platform.ID, error) { + return nil, 0, &errors.Error{ + Code: errors.ENotFound, Msg: "notification endpoint not found", } }, @@ -622,7 +625,7 @@ func TestService_handlePatchNotificationEndpoint(t *testing.T) { name: "update a notification endpoint name", fields: fields{ &mock.NotificationEndpointService{ - PatchNotificationEndpointF: func(ctx context.Context, id influxdb.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { + PatchNotificationEndpointF: func(ctx context.Context, id platform.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { if id == influxTesting.MustIDBase16("020f755c3c082000") { d := &endpoint.Slack{ Base: endpoint.Base{ @@ -678,9 +681,9 @@ func TestService_handlePatchNotificationEndpoint(t *testing.T) { name: "notification endpoint not found", fields: fields{ &mock.NotificationEndpointService{ - PatchNotificationEndpointF: func(ctx context.Context, id influxdb.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + PatchNotificationEndpointF: func(ctx context.Context, id platform.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: "notification endpoint not found", } }, @@ -775,7 +778,7 @@ func TestService_handleUpdateNotificationEndpoint(t *testing.T) { name: "update a notification endpoint name", fields: fields{ NotificationEndpointService: &mock.NotificationEndpointService{ - UpdateNotificationEndpointF: func(ctx context.Context, id influxdb.ID, edp influxdb.NotificationEndpoint, userID influxdb.ID) (influxdb.NotificationEndpoint, error) { + UpdateNotificationEndpointF: func(ctx context.Context, id platform.ID, edp influxdb.NotificationEndpoint, userID platform.ID) (influxdb.NotificationEndpoint, error) { if id == influxTesting.MustIDBase16("020f755c3c082000") { edp.SetID(id) edp.BackfillSecretKeys() @@ -826,9 +829,9 @@ func TestService_handleUpdateNotificationEndpoint(t *testing.T) { name: "notification endpoint not found", fields: fields{ NotificationEndpointService: &mock.NotificationEndpointService{ - UpdateNotificationEndpointF: func(ctx context.Context, id influxdb.ID, edp influxdb.NotificationEndpoint, userID influxdb.ID) (influxdb.NotificationEndpoint, error) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + UpdateNotificationEndpointF: func(ctx context.Context, id platform.ID, edp influxdb.NotificationEndpoint, userID platform.ID) (influxdb.NotificationEndpoint, error) { + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: "notification endpoint not found", } }, @@ -898,7 +901,7 @@ func TestService_handlePostNotificationEndpointMember(t *testing.T) { name: "add a notification endpoint member", fields: fields{ UserService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ ID: id, Name: "name", @@ -993,7 +996,7 @@ func TestService_handlePostNotificationEndpointOwner(t *testing.T) { name: "add a notification endpoint owner", fields: fields{ UserService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ ID: id, Name: "name", @@ -1138,13 +1141,13 @@ func TestNotificationEndpointService(t *testing.T) { } } -func authCtxFn(userID influxdb.ID) func(context.Context) context.Context { +func authCtxFn(userID platform.ID) func(context.Context) context.Context { return func(ctx context.Context) context.Context { return pcontext.SetAuthorizer(ctx, &influxdb.Session{UserID: userID}) } } -func withOrgID(store *tenant.Store, orgID influxdb.ID, fn func()) { +func withOrgID(store *tenant.Store, orgID platform.ID, fn func()) { backup := store.OrgIDGen defer func() { store.OrgIDGen = backup }() diff --git a/http/notification_rule.go b/http/notification_rule.go index fd7836059cc..eff9df37773 100644 --- a/http/notification_rule.go +++ b/http/notification_rule.go @@ -9,6 +9,9 @@ import ( "path" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" pctx "github.com/influxdata/influxdb/v2/context" @@ -26,7 +29,7 @@ type statusDecode struct { // NotificationRuleBackend is all services and associated parameters required to construct // the NotificationRuleBackendHandler. type NotificationRuleBackend struct { - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger AlgoWProxy FeatureProxyHandler @@ -59,7 +62,7 @@ func NewNotificationRuleBackend(log *zap.Logger, b *APIBackend) *NotificationRul // NotificationRuleHandler is the handler for the notification rule service type NotificationRuleHandler struct { *httprouter.Router - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger NotificationRuleStore influxdb.NotificationRuleStore @@ -266,12 +269,12 @@ func (h *NotificationRuleHandler) newNotificationRulesResponse(ctx context.Conte return resp, nil } -func decodeGetNotificationRuleRequest(ctx context.Context, r *http.Request) (i influxdb.ID, err error) { +func decodeGetNotificationRuleRequest(ctx context.Context, r *http.Request) (i platform.ID, err error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return i, &influxdb.Error{ - Code: influxdb.EInvalid, + return i, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } @@ -323,8 +326,8 @@ func (h *NotificationRuleHandler) handleGetNotificationRuleQuery(w http.Response } edp, err := h.NotificationEndpointService.FindNotificationEndpointByID(ctx, nr.GetEndpointID()) if err != nil { - h.HandleHTTPError(ctx, &influxdb.Error{ - Code: influxdb.EInternal, + h.HandleHTTPError(ctx, &errors.Error{ + Code: errors.EInternal, Op: "http/handleGetNotificationRuleQuery", Err: err, }, w) @@ -388,10 +391,10 @@ func decodeNotificationRuleFilter(ctx context.Context, r *http.Request) (*influx q := r.URL.Query() if orgIDStr := q.Get("orgID"); orgIDStr != "" { - orgID, err := influxdb.IDFromString(orgIDStr) + orgID, err := platform.IDFromString(orgIDStr) if err != nil { - return f, opts, &influxdb.Error{ - Code: influxdb.EInvalid, + return f, opts, &errors.Error{ + Code: errors.EInvalid, Msg: "orgID is invalid", Err: err, } @@ -418,7 +421,7 @@ func decodeUserResourceMappingFilter(ctx context.Context, r *http.Request, typ i ResourceType: typ, } if idStr := q.Get("resourceID"); idStr != "" { - id, err := influxdb.IDFromString(idStr) + id, err := platform.IDFromString(idStr) if err != nil { return nil, err } @@ -426,7 +429,7 @@ func decodeUserResourceMappingFilter(ctx context.Context, r *http.Request, typ i } if idStr := q.Get("userID"); idStr != "" { - id, err := influxdb.IDFromString(idStr) + id, err := platform.IDFromString(idStr) if err != nil { return nil, err } @@ -448,8 +451,8 @@ func decodePostNotificationRuleRequest(ctx context.Context, r *http.Request) (po buf := new(bytes.Buffer) _, err := buf.ReadFrom(r.Body) if err != nil { - return pnrr, &influxdb.Error{ - Code: influxdb.EInvalid, + return pnrr, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -457,8 +460,8 @@ func decodePostNotificationRuleRequest(ctx context.Context, r *http.Request) (po nr, err := rule.UnmarshalJSON(buf.Bytes()) if err != nil { - return pnrr, &influxdb.Error{ - Code: influxdb.EInvalid, + return pnrr, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -489,28 +492,28 @@ func decodePutNotificationRuleRequest(ctx context.Context, r *http.Request) (inf buf := new(bytes.Buffer) _, err := buf.ReadFrom(r.Body) if err != nil { - return nrc, &influxdb.Error{ - Code: influxdb.EInvalid, + return nrc, &errors.Error{ + Code: errors.EInvalid, Err: err, } } defer r.Body.Close() nr, err := rule.UnmarshalJSON(buf.Bytes()) if err != nil { - return nrc, &influxdb.Error{ - Code: influxdb.EInvalid, + return nrc, &errors.Error{ + Code: errors.EInvalid, Err: err, } } params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nrc, &influxdb.Error{ - Code: influxdb.EInvalid, + return nrc, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - i := new(influxdb.ID) + i := new(platform.ID) if err := i.DecodeFromString(id); err != nil { return nrc, err } @@ -530,7 +533,7 @@ func decodePutNotificationRuleRequest(ctx context.Context, r *http.Request) (inf } type patchNotificationRuleRequest struct { - influxdb.ID + platform.ID Update influxdb.NotificationRuleUpdate } @@ -539,13 +542,13 @@ func decodePatchNotificationRuleRequest(ctx context.Context, r *http.Request) (* params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -553,14 +556,14 @@ func decodePatchNotificationRuleRequest(ctx context.Context, r *http.Request) (* upd := &influxdb.NotificationRuleUpdate{} if err := json.NewDecoder(r.Body).Decode(upd); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: err.Error(), } } if err := upd.Valid(); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: err.Error(), } } @@ -608,7 +611,7 @@ func (h *NotificationRuleHandler) handlePostNotificationRule(w http.ResponseWrit func (h *NotificationRuleHandler) mapNewNotificationRuleLabels(ctx context.Context, nrc influxdb.NotificationRuleCreate, labels []string) []*influxdb.Label { var ls []*influxdb.Label for _, sid := range labels { - var lid influxdb.ID + var lid platform.ID err := lid.DecodeFromString(sid) if err != nil { @@ -773,7 +776,7 @@ func (n *notificationRuleDecoder) UnmarshalJSON(b []byte) error { // CreateNotificationRule creates a new NotificationRule from a NotificationRuleCreate // the Status on the NotificationRuleCreate is used to determine the status (active/inactive) of the associated Task -func (s *NotificationRuleService) CreateNotificationRule(ctx context.Context, nr influxdb.NotificationRuleCreate, userID influxdb.ID) error { +func (s *NotificationRuleService) CreateNotificationRule(ctx context.Context, nr influxdb.NotificationRuleCreate, userID platform.ID) error { var resp notificationRuleDecoder err := s.Client. PostJSON(notificationRuleCreateEncoder{nrc: nr}, prefixNotificationRules). @@ -791,7 +794,7 @@ func (s *NotificationRuleService) CreateNotificationRule(ctx context.Context, nr } // FindNotificationRuleByID finds and returns one Notification Rule with a matching ID -func (s *NotificationRuleService) FindNotificationRuleByID(ctx context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { +func (s *NotificationRuleService) FindNotificationRuleByID(ctx context.Context, id platform.ID) (influxdb.NotificationRule, error) { var resp notificationRuleResponse err := s.Client. Get(getNotificationRulesIDPath(id)). @@ -843,7 +846,7 @@ func (s *NotificationRuleService) FindNotificationRules(ctx context.Context, fil // UpdateNotificationRule updates a single notification rule. // Returns the new notification rule after update. -func (s *NotificationRuleService) UpdateNotificationRule(ctx context.Context, id influxdb.ID, nr influxdb.NotificationRuleCreate, userID influxdb.ID) (influxdb.NotificationRule, error) { +func (s *NotificationRuleService) UpdateNotificationRule(ctx context.Context, id platform.ID, nr influxdb.NotificationRuleCreate, userID platform.ID) (influxdb.NotificationRule, error) { var resp notificationRuleDecoder err := s.Client. PutJSON(notificationRuleCreateEncoder{nrc: nr}, getNotificationRulesIDPath(id)). @@ -858,7 +861,7 @@ func (s *NotificationRuleService) UpdateNotificationRule(ctx context.Context, id // PatchNotificationRule updates a single notification rule with changeset. // Returns the new notification rule state after update. -func (s *NotificationRuleService) PatchNotificationRule(ctx context.Context, id influxdb.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { +func (s *NotificationRuleService) PatchNotificationRule(ctx context.Context, id platform.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { var resp notificationRuleDecoder err := s.Client. PatchJSON(&upd, getNotificationRulesIDPath(id)). @@ -872,12 +875,12 @@ func (s *NotificationRuleService) PatchNotificationRule(ctx context.Context, id } // DeleteNotificationRule removes a notification rule by ID. -func (s *NotificationRuleService) DeleteNotificationRule(ctx context.Context, id influxdb.ID) error { +func (s *NotificationRuleService) DeleteNotificationRule(ctx context.Context, id platform.ID) error { return s.Client. Delete(getNotificationRulesIDPath(id)). Do(ctx) } -func getNotificationRulesIDPath(id influxdb.ID) string { +func getNotificationRulesIDPath(id platform.ID) string { return path.Join(prefixNotificationRules, id.String()) } diff --git a/http/notification_rule_test.go b/http/notification_rule_test.go index 7116730c89c..62123d0419b 100644 --- a/http/notification_rule_test.go +++ b/http/notification_rule_test.go @@ -5,6 +5,8 @@ import ( "encoding/json" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" "github.com/influxdata/influxdb/v2/notification" @@ -23,7 +25,7 @@ func NewMockNotificationRuleBackend(t *testing.T) *NotificationRuleBackend { UserService: mock.NewUserService(), OrganizationService: mock.NewOrganizationService(), TaskService: &mock.TaskService{ - FindTaskByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + FindTaskByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { return &influxdb.Task{Status: "active"}, nil }, }, @@ -49,16 +51,16 @@ func Test_newNotificationRuleResponses(t *testing.T) { Descending: true, }, filter: influxdb.NotificationRuleFilter{ - OrgID: influxTesting.IDPtr(influxdb.ID(2)), + OrgID: influxTesting.IDPtr(platform.ID(2)), }, nrs: []influxdb.NotificationRule{ &rule.Slack{ Channel: "ch1", MessageTemplate: "message 1{var1}", Base: rule.Base{ - ID: influxdb.ID(1), - OrgID: influxdb.ID(2), - OwnerID: influxdb.ID(3), + ID: platform.ID(1), + OrgID: platform.ID(2), + OwnerID: platform.ID(3), EndpointID: 4, Name: "name1", Description: "desc1", @@ -87,9 +89,9 @@ func Test_newNotificationRuleResponses(t *testing.T) { &rule.PagerDuty{ MessageTemplate: "body 2{var2}", Base: rule.Base{ - ID: influxdb.ID(11), - OrgID: influxdb.ID(2), - OwnerID: influxdb.ID(33), + ID: platform.ID(11), + OrgID: platform.ID(2), + OwnerID: platform.ID(33), EndpointID: 44, Name: "name2", Description: "desc2", @@ -217,9 +219,9 @@ func Test_newNotificationRuleResponse(t *testing.T) { Channel: "ch1", MessageTemplate: "message 1{var1}", Base: rule.Base{ - ID: influxdb.ID(1), - OrgID: influxdb.ID(2), - OwnerID: influxdb.ID(3), + ID: platform.ID(1), + OrgID: platform.ID(2), + OwnerID: platform.ID(3), EndpointID: 4, Name: "name1", Description: "desc1", diff --git a/http/points/points_parser.go b/http/points/points_parser.go index 1b8582f4075..82f9d4f6659 100644 --- a/http/points/points_parser.go +++ b/http/points/points_parser.go @@ -8,7 +8,9 @@ import ( "io/ioutil" "time" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + io2 "github.com/influxdata/influxdb/v2/kit/io" "github.com/influxdata/influxdb/v2/kit/tracing" "github.com/influxdata/influxdb/v2/models" @@ -44,22 +46,22 @@ type Parser struct { } // Parse parses the points from an io.ReadCloser for a specific Bucket. -func (pw *Parser) Parse(ctx context.Context, orgID, bucketID influxdb.ID, rc io.ReadCloser) (*ParsedPoints, error) { +func (pw *Parser) Parse(ctx context.Context, orgID, bucketID platform.ID, rc io.ReadCloser) (*ParsedPoints, error) { span, ctx := opentracing.StartSpanFromContext(ctx, "write points") defer span.Finish() return pw.parsePoints(ctx, orgID, bucketID, rc) } -func (pw *Parser) parsePoints(ctx context.Context, orgID, bucketID influxdb.ID, rc io.ReadCloser) (*ParsedPoints, error) { +func (pw *Parser) parsePoints(ctx context.Context, orgID, bucketID platform.ID, rc io.ReadCloser) (*ParsedPoints, error) { data, err := readAll(ctx, rc) if err != nil { - code := influxdb.EInternal + code := errors2.EInternal if errors.Is(err, ErrMaxBatchSizeExceeded) { - code = influxdb.ETooLarge + code = errors2.ETooLarge } else if errors.Is(err, gzip.ErrHeader) || errors.Is(err, gzip.ErrChecksum) { - code = influxdb.EInvalid + code = errors2.EInvalid } - return nil, &influxdb.Error{ + return nil, &errors2.Error{ Code: code, Op: opPointsWriter, Msg: msgUnableToReadData, @@ -69,9 +71,9 @@ func (pw *Parser) parsePoints(ctx context.Context, orgID, bucketID influxdb.ID, requestBytes := len(data) if requestBytes == 0 { - return nil, &influxdb.Error{ + return nil, &errors2.Error{ Op: opPointsWriter, - Code: influxdb.EInvalid, + Code: errors2.EInvalid, Msg: msgWritingRequiresPoints, } } @@ -84,7 +86,7 @@ func (pw *Parser) parsePoints(ctx context.Context, orgID, bucketID influxdb.ID, if err != nil { log.Error("Error parsing points", zap.Error(err)) - code := influxdb.EInvalid + code := errors2.EInvalid // TODO - backport these // if errors.Is(err, models.ErrLimitMaxBytesExceeded) || // errors.Is(err, models.ErrLimitMaxLinesExceeded) || @@ -92,7 +94,7 @@ func (pw *Parser) parsePoints(ctx context.Context, orgID, bucketID influxdb.ID, // code = influxdb.ETooLarge // } - return nil, &influxdb.Error{ + return nil, &errors2.Error{ Code: code, Op: opPointsWriter, Msg: "", diff --git a/http/query_handler.go b/http/query_handler.go index c6553fd96df..537c826e3ca 100644 --- a/http/query_handler.go +++ b/http/query_handler.go @@ -12,6 +12,9 @@ import ( "sort" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/NYTimes/gziphandler" "github.com/influxdata/flux" "github.com/influxdata/flux/ast" @@ -41,7 +44,7 @@ const ( // FluxBackend is all services and associated parameters required to construct // the FluxHandler. type FluxBackend struct { - influxdb.HTTPErrorHandler + errors2.HTTPErrorHandler log *zap.Logger QueryEventRecorder metric.EventRecorder @@ -77,7 +80,7 @@ type HTTPDialect interface { // FluxHandler implements handling flux queries. type FluxHandler struct { *httprouter.Router - influxdb.HTTPErrorHandler + errors2.HTTPErrorHandler log *zap.Logger Now func() time.Time @@ -133,7 +136,7 @@ func (h *FluxHandler) handleQuery(w http.ResponseWriter, r *http.Request) { // TODO(desa): I really don't like how we're recording the usage metrics here // Ideally this will be moved when we solve https://github.com/influxdata/influxdb/issues/13403 - var orgID influxdb.ID + var orgID platform.ID var requestBytes int sw := kithttp.NewStatusResponseWriter(w) w = sw @@ -149,8 +152,8 @@ func (h *FluxHandler) handleQuery(w http.ResponseWriter, r *http.Request) { a, err := pcontext.GetAuthorizer(ctx) if err != nil { - err := &influxdb.Error{ - Code: influxdb.EUnauthorized, + err := &errors2.Error{ + Code: errors2.EUnauthorized, Msg: "authorization is invalid or missing in the query request", Op: op, Err: err, @@ -161,8 +164,8 @@ func (h *FluxHandler) handleQuery(w http.ResponseWriter, r *http.Request) { req, n, err := decodeProxyQueryRequest(ctx, r, a, h.OrganizationService) if err != nil && err != influxdb.ErrAuthorizerNotSupported { - err := &influxdb.Error{ - Code: influxdb.EInvalid, + err := &errors2.Error{ + Code: errors2.EInvalid, Msg: "failed to decode request body", Op: op, Err: err, @@ -182,8 +185,8 @@ func (h *FluxHandler) handleQuery(w http.ResponseWriter, r *http.Request) { hd, ok := req.Dialect.(HTTPDialect) if !ok { - err := &influxdb.Error{ - Code: influxdb.EInvalid, + err := &errors2.Error{ + Code: errors2.EInvalid, Msg: fmt.Sprintf("unsupported dialect over HTTP: %T", req.Dialect), Op: op, } @@ -225,8 +228,8 @@ func (h *FluxHandler) postFluxAST(w http.ResponseWriter, r *http.Request) { err := json.NewDecoder(r.Body).Decode(&request) if err != nil { - h.HandleHTTPError(ctx, &influxdb.Error{ - Code: influxdb.EInvalid, + h.HandleHTTPError(ctx, &errors2.Error{ + Code: errors2.EInvalid, Msg: "invalid json", Err: err, }, w) @@ -235,8 +238,8 @@ func (h *FluxHandler) postFluxAST(w http.ResponseWriter, r *http.Request) { pkg, err := query.Parse(h.FluxLanguageService, request.Query) if err != nil { - h.HandleHTTPError(ctx, &influxdb.Error{ - Code: influxdb.EInvalid, + h.HandleHTTPError(ctx, &errors2.Error{ + Code: errors2.EInvalid, Msg: "invalid AST", Err: err, }, w) @@ -262,8 +265,8 @@ func (h *FluxHandler) postQueryAnalyze(w http.ResponseWriter, r *http.Request) { var req QueryRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - h.HandleHTTPError(ctx, &influxdb.Error{ - Code: influxdb.EInvalid, + h.HandleHTTPError(ctx, &errors2.Error{ + Code: errors2.EInvalid, Msg: "invalid json", Err: err, }, w) diff --git a/http/query_handler_test.go b/http/query_handler_test.go index d42d2558870..87810b60387 100644 --- a/http/query_handler_test.go +++ b/http/query_handler_test.go @@ -15,6 +15,9 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" "github.com/influxdata/flux" "github.com/influxdata/flux/csv" @@ -35,7 +38,7 @@ import ( ) func TestFluxService_Query(t *testing.T) { - orgID, err := influxdb.IDFromString("abcdabcdabcdabcd") + orgID, err := platform.IDFromString("abcdabcdabcdabcd") if err != nil { t.Fatal(err) } @@ -133,7 +136,7 @@ func TestFluxService_Query(t *testing.T) { } func TestFluxQueryService_Query(t *testing.T) { - var orgID influxdb.ID + var orgID platform.ID orgID.DecodeFromString("aaaaaaaaaaaaaaaa") tests := []struct { name string @@ -336,8 +339,8 @@ func TestFluxHandler_PostQuery_Errors(t *testing.T) { OrganizationService: orgSVC, ProxyQueryService: &mock.ProxyQueryService{ QueryF: func(ctx context.Context, w io.Writer, req *query.ProxyRequest) (flux.Statistics, error) { - return flux.Statistics{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return flux.Statistics{}, &errors.Error{ + Code: errors.EInvalid, Msg: "some query error", } }, @@ -371,7 +374,7 @@ func TestFluxHandler_PostQuery_Errors(t *testing.T) { t.Fatal(err) } - var ierr influxdb.Error + var ierr errors.Error if err := json.Unmarshal(body, &ierr); err != nil { t.Logf("failed to json unmarshal into influxdb.error: %q", body) t.Fatal(err) @@ -402,7 +405,7 @@ func TestFluxHandler_PostQuery_Errors(t *testing.T) { } body := w.Body.Bytes() - var ierr influxdb.Error + var ierr errors.Error if err := json.Unmarshal(body, &ierr); err != nil { t.Logf("failed to json unmarshal into influxdb.error: %q", body) t.Fatal(err) @@ -440,13 +443,13 @@ func TestFluxHandler_PostQuery_Errors(t *testing.T) { body := w.Body.Bytes() t.Logf("%s", body) - var ierr influxdb.Error + var ierr errors.Error if err := json.Unmarshal(body, &ierr); err != nil { t.Logf("failed to json unmarshal into influxdb.error: %q", body) t.Fatal(err) } - if got, want := ierr.Code, influxdb.EInvalid; got != want { + if got, want := ierr.Code, errors.EInvalid; got != want { t.Fatalf("unexpected error code -want/+got:\n\t- %v\n\t+ %v", want, got) } if ierr.Msg != "some query error" { @@ -459,7 +462,7 @@ func TestFluxService_Query_gzip(t *testing.T) { // orgService is just to mock out orgs by returning // the same org every time. orgService := &influxmock.OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: id, Name: id.String(), @@ -468,8 +471,8 @@ func TestFluxService_Query_gzip(t *testing.T) { FindOrganizationF: func(ctx context.Context, filter influxdb.OrganizationFilter) (*influxdb.Organization, error) { return &influxdb.Organization{ - ID: influxdb.ID(1), - Name: influxdb.ID(1).String(), + ID: platform.ID(1), + Name: platform.ID(1).String(), }, nil }, } @@ -490,8 +493,8 @@ func TestFluxService_Query_gzip(t *testing.T) { authService := &influxmock.AuthorizationService{ FindAuthorizationByTokenFn: func(ctx context.Context, token string) (*influxdb.Authorization, error) { return &influxdb.Authorization{ - ID: influxdb.ID(1), - OrgID: influxdb.ID(1), + ID: platform.ID(1), + OrgID: platform.ID(1), Permissions: influxdb.OperPermissions(), }, nil }, @@ -516,7 +519,7 @@ func TestFluxService_Query_gzip(t *testing.T) { auth.AuthorizationService = authService auth.Handler = fluxHandler auth.UserService = &influxmock.UserService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{}, nil }, } @@ -597,7 +600,7 @@ func benchmarkQuery(b *testing.B, disableCompression bool) { // orgService is just to mock out orgs by returning // the same org every time. orgService := &influxmock.OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: id, Name: id.String(), @@ -606,8 +609,8 @@ func benchmarkQuery(b *testing.B, disableCompression bool) { FindOrganizationF: func(ctx context.Context, filter influxdb.OrganizationFilter) (*influxdb.Organization, error) { return &influxdb.Organization{ - ID: influxdb.ID(1), - Name: influxdb.ID(1).String(), + ID: platform.ID(1), + Name: platform.ID(1).String(), }, nil }, } @@ -628,8 +631,8 @@ func benchmarkQuery(b *testing.B, disableCompression bool) { authService := &influxmock.AuthorizationService{ FindAuthorizationByTokenFn: func(ctx context.Context, token string) (*influxdb.Authorization, error) { return &influxdb.Authorization{ - ID: influxdb.ID(1), - OrgID: influxdb.ID(1), + ID: platform.ID(1), + OrgID: platform.ID(1), Permissions: influxdb.OperPermissions(), }, nil }, diff --git a/http/query_test.go b/http/query_test.go index aabe4fa9265..707025c8329 100644 --- a/http/query_test.go +++ b/http/query_test.go @@ -11,6 +11,8 @@ import ( "testing" "time" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/influxdata/flux" @@ -393,7 +395,7 @@ func Test_decodeQueryRequest(t *testing.T) { svc: &mock.OrganizationService{ FindOrganizationF: func(ctx context.Context, filter platform.OrganizationFilter) (*platform.Organization, error) { return &platform.Organization{ - ID: func() platform.ID { s, _ := platform.IDFromString("deadbeefdeadbeef"); return *s }(), + ID: func() platform2.ID { s, _ := platform2.IDFromString("deadbeefdeadbeef"); return *s }(), }, nil }, }, @@ -407,7 +409,7 @@ func Test_decodeQueryRequest(t *testing.T) { Header: func(x bool) *bool { return &x }(true), }, Org: &platform.Organization{ - ID: func() platform.ID { s, _ := platform.IDFromString("deadbeefdeadbeef"); return *s }(), + ID: func() platform2.ID { s, _ := platform2.IDFromString("deadbeefdeadbeef"); return *s }(), }, }, }, @@ -422,7 +424,7 @@ func Test_decodeQueryRequest(t *testing.T) { svc: &mock.OrganizationService{ FindOrganizationF: func(ctx context.Context, filter platform.OrganizationFilter) (*platform.Organization, error) { return &platform.Organization{ - ID: func() platform.ID { s, _ := platform.IDFromString("deadbeefdeadbeef"); return *s }(), + ID: func() platform2.ID { s, _ := platform2.IDFromString("deadbeefdeadbeef"); return *s }(), }, nil }, }, @@ -436,7 +438,7 @@ func Test_decodeQueryRequest(t *testing.T) { Header: func(x bool) *bool { return &x }(true), }, Org: &platform.Organization{ - ID: func() platform.ID { s, _ := platform.IDFromString("deadbeefdeadbeef"); return *s }(), + ID: func() platform2.ID { s, _ := platform2.IDFromString("deadbeefdeadbeef"); return *s }(), }, }, }, @@ -508,14 +510,14 @@ func Test_decodeProxyQueryRequest(t *testing.T) { svc: &mock.OrganizationService{ FindOrganizationF: func(ctx context.Context, filter platform.OrganizationFilter) (*platform.Organization, error) { return &platform.Organization{ - ID: func() platform.ID { s, _ := platform.IDFromString("deadbeefdeadbeef"); return *s }(), + ID: func() platform2.ID { s, _ := platform2.IDFromString("deadbeefdeadbeef"); return *s }(), }, nil }, }, }, want: &query.ProxyRequest{ Request: query.Request{ - OrganizationID: func() platform.ID { s, _ := platform.IDFromString("deadbeefdeadbeef"); return *s }(), + OrganizationID: func() platform2.ID { s, _ := platform2.IDFromString("deadbeefdeadbeef"); return *s }(), Compiler: lang.FluxCompiler{ Query: "from()", }, @@ -540,14 +542,14 @@ func Test_decodeProxyQueryRequest(t *testing.T) { svc: &mock.OrganizationService{ FindOrganizationF: func(ctx context.Context, filter platform.OrganizationFilter) (*platform.Organization, error) { return &platform.Organization{ - ID: func() platform.ID { s, _ := platform.IDFromString("deadbeefdeadbeef"); return *s }(), + ID: func() platform2.ID { s, _ := platform2.IDFromString("deadbeefdeadbeef"); return *s }(), }, nil }, }, }, want: &query.ProxyRequest{ Request: query.Request{ - OrganizationID: func() platform.ID { s, _ := platform.IDFromString("deadbeefdeadbeef"); return *s }(), + OrganizationID: func() platform2.ID { s, _ := platform2.IDFromString("deadbeefdeadbeef"); return *s }(), Compiler: lang.FluxCompiler{ Extern: []byte(externJSON), Query: `from(bucket: "mybucket")`, @@ -572,14 +574,14 @@ func Test_decodeProxyQueryRequest(t *testing.T) { svc: &mock.OrganizationService{ FindOrganizationF: func(ctx context.Context, filter platform.OrganizationFilter) (*platform.Organization, error) { return &platform.Organization{ - ID: func() platform.ID { s, _ := platform.IDFromString("deadbeefdeadbeef"); return *s }(), + ID: func() platform2.ID { s, _ := platform2.IDFromString("deadbeefdeadbeef"); return *s }(), }, nil }, }, }, want: &query.ProxyRequest{ Request: query.Request{ - OrganizationID: func() platform.ID { s, _ := platform.IDFromString("deadbeefdeadbeef"); return *s }(), + OrganizationID: func() platform2.ID { s, _ := platform2.IDFromString("deadbeefdeadbeef"); return *s }(), Compiler: lang.FluxCompiler{ Query: `from(bucket: "mybucket")`, }, diff --git a/http/requests.go b/http/requests.go index 994ea619a2d..5cb2b43ed76 100644 --- a/http/requests.go +++ b/http/requests.go @@ -4,6 +4,9 @@ import ( "context" "net/http" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + platform "github.com/influxdata/influxdb/v2" ) @@ -28,7 +31,7 @@ const ( func queryOrganization(ctx context.Context, r *http.Request, svc platform.OrganizationService) (o *platform.Organization, err error) { filter := platform.OrganizationFilter{} if organization := r.URL.Query().Get(Org); organization != "" { - if id, err := platform.IDFromString(organization); err == nil { + if id, err := platform2.IDFromString(organization); err == nil { filter.ID = id } else { filter.Name = &organization @@ -36,7 +39,7 @@ func queryOrganization(ctx context.Context, r *http.Request, svc platform.Organi } if reqID := r.URL.Query().Get(OrgID); reqID != "" { - filter.ID, err = platform.IDFromString(reqID) + filter.ID, err = platform2.IDFromString(reqID) if err != nil { return nil, err } @@ -51,24 +54,24 @@ func queryOrganization(ctx context.Context, r *http.Request, svc platform.Organi // This will try to find the bucket using an ID string or // the name. It interprets the &bucket= parameter as either the name // or the ID. -func queryBucket(ctx context.Context, orgID platform.ID, r *http.Request, svc platform.BucketService) (b *platform.Bucket, err error) { +func queryBucket(ctx context.Context, orgID platform2.ID, r *http.Request, svc platform.BucketService) (b *platform.Bucket, err error) { filter := platform.BucketFilter{OrganizationID: &orgID} if bucket := r.URL.Query().Get(Bucket); bucket != "" { - if id, err := platform.IDFromString(bucket); err == nil { + if id, err := platform2.IDFromString(bucket); err == nil { filter.ID = id } else { filter.Name = &bucket } } if reqID := r.URL.Query().Get(BucketID); reqID != "" { - filter.ID, err = platform.IDFromString(reqID) + filter.ID, err = platform2.IDFromString(reqID) if err != nil { return nil, err } } if filter.ID == nil && filter.Name == nil { - return nil, &platform.Error{ - Code: platform.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "Please provide either bucketID or bucket", } } diff --git a/http/requests_test.go b/http/requests_test.go index f1b1f9bcadd..efb59b53bc5 100644 --- a/http/requests_test.go +++ b/http/requests_test.go @@ -7,6 +7,9 @@ import ( "reflect" "testing" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + platform "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" ) @@ -26,20 +29,20 @@ func Test_queryOrganization(t *testing.T) { { name: "org id finds organization", want: &platform.Organization{ - ID: platform.ID(1), + ID: platform2.ID(1), }, args: args{ ctx: context.Background(), r: httptest.NewRequest(http.MethodPost, "/api/v2/query?orgID=0000000000000001", nil), svc: &mock.OrganizationService{ FindOrganizationF: func(ctx context.Context, filter platform.OrganizationFilter) (*platform.Organization, error) { - if *filter.ID == platform.ID(1) { + if *filter.ID == platform2.ID(1) { return &platform.Organization{ - ID: platform.ID(1), + ID: platform2.ID(1), }, nil } - return nil, &platform.Error{ - Code: platform.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unknown org name", } }, @@ -57,7 +60,7 @@ func Test_queryOrganization(t *testing.T) { { name: "org name finds organization", want: &platform.Organization{ - ID: platform.ID(1), + ID: platform2.ID(1), Name: "org1", }, args: args{ @@ -67,12 +70,12 @@ func Test_queryOrganization(t *testing.T) { FindOrganizationF: func(ctx context.Context, filter platform.OrganizationFilter) (*platform.Organization, error) { if *filter.Name == "org1" { return &platform.Organization{ - ID: platform.ID(1), + ID: platform2.ID(1), Name: "org1", }, nil } - return nil, &platform.Error{ - Code: platform.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unknown org name", } }, @@ -82,20 +85,20 @@ func Test_queryOrganization(t *testing.T) { { name: "org id as org finds organization", want: &platform.Organization{ - ID: platform.ID(1), + ID: platform2.ID(1), }, args: args{ ctx: context.Background(), r: httptest.NewRequest(http.MethodPost, "/api/v2/query?org=0000000000000001", nil), svc: &mock.OrganizationService{ FindOrganizationF: func(ctx context.Context, filter platform.OrganizationFilter) (*platform.Organization, error) { - if *filter.ID == platform.ID(1) { + if *filter.ID == platform2.ID(1) { return &platform.Organization{ - ID: platform.ID(1), + ID: platform2.ID(1), }, nil } - return nil, &platform.Error{ - Code: platform.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unknown org name", } }, @@ -132,20 +135,20 @@ func Test_queryBucket(t *testing.T) { { name: "bucket id finds bucket", want: &platform.Bucket{ - ID: platform.ID(1), + ID: platform2.ID(1), }, args: args{ ctx: context.Background(), r: httptest.NewRequest(http.MethodPost, "/api/v2/query?bucketID=0000000000000001", nil), svc: &mock.BucketService{ FindBucketFn: func(ctx context.Context, filter platform.BucketFilter) (*platform.Bucket, error) { - if *filter.ID == platform.ID(1) { + if *filter.ID == platform2.ID(1) { return &platform.Bucket{ - ID: platform.ID(1), + ID: platform2.ID(1), }, nil } - return nil, &platform.Error{ - Code: platform.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unknown org name", } }, @@ -163,7 +166,7 @@ func Test_queryBucket(t *testing.T) { { name: "bucket name finds bucket", want: &platform.Bucket{ - ID: platform.ID(1), + ID: platform2.ID(1), Name: "bucket1", }, args: args{ @@ -173,12 +176,12 @@ func Test_queryBucket(t *testing.T) { FindBucketFn: func(ctx context.Context, filter platform.BucketFilter) (*platform.Bucket, error) { if *filter.Name == "bucket1" { return &platform.Bucket{ - ID: platform.ID(1), + ID: platform2.ID(1), Name: "bucket1", }, nil } - return nil, &platform.Error{ - Code: platform.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unknown org name", } }, @@ -188,20 +191,20 @@ func Test_queryBucket(t *testing.T) { { name: "bucket id as bucket finds bucket", want: &platform.Bucket{ - ID: platform.ID(1), + ID: platform2.ID(1), }, args: args{ ctx: context.Background(), r: httptest.NewRequest(http.MethodPost, "/api/v2/query?bucket=0000000000000001", nil), svc: &mock.BucketService{ FindBucketFn: func(ctx context.Context, filter platform.BucketFilter) (*platform.Bucket, error) { - if *filter.ID == platform.ID(1) { + if *filter.ID == platform2.ID(1) { return &platform.Bucket{ - ID: platform.ID(1), + ID: platform2.ID(1), }, nil } - return nil, &platform.Error{ - Code: platform.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unknown bucket name", } }, @@ -211,20 +214,20 @@ func Test_queryBucket(t *testing.T) { { name: "invalid orgID fails to return bucket", want: &platform.Bucket{ - ID: platform.ID(1), + ID: platform2.ID(1), }, args: args{ ctx: context.Background(), r: httptest.NewRequest(http.MethodPost, "/api/v2/query?bucket=0000000000000001", nil), svc: &mock.BucketService{ FindBucketFn: func(ctx context.Context, filter platform.BucketFilter) (*platform.Bucket, error) { - if *filter.OrganizationID == platform.ID(1) { + if *filter.OrganizationID == platform2.ID(1) { return &platform.Bucket{ - ID: platform.ID(1), + ID: platform2.ID(1), }, nil } - return nil, &platform.Error{ - Code: platform.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unknown bucket", } }, @@ -233,7 +236,7 @@ func Test_queryBucket(t *testing.T) { }} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := queryBucket(tt.args.ctx, platform.ID(1), tt.args.r, tt.args.svc) + got, err := queryBucket(tt.args.ctx, platform2.ID(1), tt.args.r, tt.args.svc) if (err != nil) != tt.wantErr { t.Errorf("queryBucket() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/http/restore_service.go b/http/restore_service.go index 2369ded6649..428ddae5d01 100644 --- a/http/restore_service.go +++ b/http/restore_service.go @@ -10,6 +10,9 @@ import ( "net/http" "strconv" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/tracing" @@ -19,7 +22,7 @@ import ( // RestoreBackend is all services and associated parameters required to construct the RestoreHandler. type RestoreBackend struct { Logger *zap.Logger - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler RestoreService influxdb.RestoreService } @@ -37,7 +40,7 @@ func NewRestoreBackend(b *APIBackend) *RestoreBackend { // RestoreHandler is http handler for restore service. type RestoreHandler struct { *httprouter.Router - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler Logger *zap.Logger RestoreService influxdb.RestoreService @@ -167,7 +170,7 @@ func (s *RestoreService) RestoreKVStore(ctx context.Context, r io.Reader) error return nil } -func (s *RestoreService) RestoreBucket(ctx context.Context, id influxdb.ID, dbi []byte) (map[uint64]uint64, error) { +func (s *RestoreService) RestoreBucket(ctx context.Context, id platform.ID, dbi []byte) (map[uint64]uint64, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() diff --git a/http/router.go b/http/router.go index 7315ff0468f..ada7e3f4dac 100644 --- a/http/router.go +++ b/http/router.go @@ -7,11 +7,12 @@ import ( "runtime/debug" "sync" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/go-stack/stack" "github.com/influxdata/httprouter" - platform "github.com/influxdata/influxdb/v2" kithttp "github.com/influxdata/influxdb/v2/kit/transport/http" influxlogger "github.com/influxdata/influxdb/v2/logger" "go.uber.org/zap" @@ -19,7 +20,7 @@ import ( ) // NewRouter returns a new router with a 404 handler, a 405 handler, and a panic handler. -func NewRouter(h platform.HTTPErrorHandler) *httprouter.Router { +func NewRouter(h errors.HTTPErrorHandler) *httprouter.Router { b := baseHandler{HTTPErrorHandler: h} router := httprouter.New() router.NotFound = http.HandlerFunc(b.notFound) @@ -33,14 +34,14 @@ func NewRouter(h platform.HTTPErrorHandler) *httprouter.Router { func NewBaseChiRouter(api *kithttp.API) chi.Router { router := chi.NewRouter() router.NotFound(func(w http.ResponseWriter, r *http.Request) { - api.Err(w, r, &platform.Error{ - Code: platform.ENotFound, + api.Err(w, r, &errors.Error{ + Code: errors.ENotFound, Msg: "path not found", }) }) router.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) { - api.Err(w, r, &platform.Error{ - Code: platform.EMethodNotAllowed, + api.Err(w, r, &errors.Error{ + Code: errors.EMethodNotAllowed, Msg: fmt.Sprintf("allow: %s", w.Header().Get("Allow")), }) @@ -55,14 +56,14 @@ func NewBaseChiRouter(api *kithttp.API) chi.Router { } type baseHandler struct { - platform.HTTPErrorHandler + errors.HTTPErrorHandler } // notFound represents a 404 handler that return a JSON response. func (h baseHandler) notFound(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - pe := &platform.Error{ - Code: platform.ENotFound, + pe := &errors.Error{ + Code: errors.ENotFound, Msg: "path not found", } @@ -73,8 +74,8 @@ func (h baseHandler) notFound(w http.ResponseWriter, r *http.Request) { func (h baseHandler) methodNotAllowed(w http.ResponseWriter, r *http.Request) { ctx := r.Context() allow := w.Header().Get("Allow") - pe := &platform.Error{ - Code: platform.EMethodNotAllowed, + pe := &errors.Error{ + Code: errors.EMethodNotAllowed, Msg: fmt.Sprintf("allow: %s", allow), } @@ -85,8 +86,8 @@ func (h baseHandler) methodNotAllowed(w http.ResponseWriter, r *http.Request) { // It returns a json response with http status code 500 and the recovered error message. func (h baseHandler) panic(w http.ResponseWriter, r *http.Request, rcv interface{}) { ctx := r.Context() - pe := &platform.Error{ - Code: platform.EInternal, + pe := &errors.Error{ + Code: errors.EInternal, Msg: "a panic has occurred", Err: fmt.Errorf("%s: %v", r.URL.String(), rcv), } @@ -109,8 +110,8 @@ func panicMW(api *kithttp.API) func(http.Handler) http.Handler { return } - pe := &platform.Error{ - Code: platform.EInternal, + pe := &errors.Error{ + Code: errors.EInternal, Msg: "a panic has occurred", Err: fmt.Errorf("%s: %v", r.URL.String(), panicErr), } diff --git a/http/scraper_service.go b/http/scraper_service.go index 31f5b33a872..c43210d8dee 100644 --- a/http/scraper_service.go +++ b/http/scraper_service.go @@ -8,6 +8,9 @@ import ( "net/http" "path" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" pctx "github.com/influxdata/influxdb/v2/context" @@ -22,7 +25,7 @@ const ( // ScraperBackend is all services and associated parameters required to construct // the ScraperHandler. type ScraperBackend struct { - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger ScraperStorageService influxdb.ScraperTargetStoreService @@ -51,7 +54,7 @@ func NewScraperBackend(log *zap.Logger, b *APIBackend) *ScraperBackend { // ScraperHandler represents an HTTP API handler for scraper targets. type ScraperHandler struct { *httprouter.Router - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger UserService influxdb.UserService UserResourceMappingService influxdb.UserResourceMappingService @@ -245,9 +248,9 @@ func decodeScraperTargetsRequest(ctx context.Context, r *http.Request) (*getScra qp := r.URL.Query() req := &getScraperTargetsRequest{} - initialID := influxdb.InvalidID() + initialID := platform.InvalidID() if ids, ok := qp["id"]; ok { - req.filter.IDs = make(map[influxdb.ID]bool) + req.filter.IDs = make(map[platform.ID]bool) for _, id := range ids { i := initialID if err := i.DecodeFromString(id); err != nil { @@ -260,7 +263,7 @@ func decodeScraperTargetsRequest(ctx context.Context, r *http.Request) (*getScra req.filter.Name = &name } if orgID := qp.Get("orgID"); orgID != "" { - id := influxdb.InvalidID() + id := platform.InvalidID() if err := id.DecodeFromString(orgID); err != nil { return nil, err } @@ -320,17 +323,17 @@ func decodeScraperTargetAddRequest(ctx context.Context, r *http.Request) (*influ return req, nil } -func decodeScraperTargetIDRequest(ctx context.Context, r *http.Request) (*influxdb.ID, error) { +func decodeScraperTargetIDRequest(ctx context.Context, r *http.Request) (*platform.ID, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -403,10 +406,10 @@ func (s *ScraperService) ListTargets(ctx context.Context, filter influxdb.Scrape // UpdateTarget updates a single scraper target with changeset. // Returns the new target state after update. -func (s *ScraperService) UpdateTarget(ctx context.Context, update *influxdb.ScraperTarget, userID influxdb.ID) (*influxdb.ScraperTarget, error) { +func (s *ScraperService) UpdateTarget(ctx context.Context, update *influxdb.ScraperTarget, userID platform.ID) (*influxdb.ScraperTarget, error) { if !update.ID.Valid() { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Op: s.OpPrefix + influxdb.OpUpdateTarget, Msg: "provided scraper target ID has invalid format", } @@ -447,22 +450,22 @@ func (s *ScraperService) UpdateTarget(ctx context.Context, update *influxdb.Scra } // AddTarget creates a new scraper target and sets target.ID with the new identifier. -func (s *ScraperService) AddTarget(ctx context.Context, target *influxdb.ScraperTarget, userID influxdb.ID) error { +func (s *ScraperService) AddTarget(ctx context.Context, target *influxdb.ScraperTarget, userID platform.ID) error { url, err := NewURL(s.Addr, prefixTargets) if err != nil { return err } if !target.OrgID.Valid() { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "provided organization ID has invalid format", Op: s.OpPrefix + influxdb.OpAddTarget, } } if !target.BucketID.Valid() { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "provided bucket ID has invalid format", Op: s.OpPrefix + influxdb.OpAddTarget, } @@ -503,7 +506,7 @@ func (s *ScraperService) AddTarget(ctx context.Context, target *influxdb.Scraper } // RemoveTarget removes a scraper target by ID. -func (s *ScraperService) RemoveTarget(ctx context.Context, id influxdb.ID) error { +func (s *ScraperService) RemoveTarget(ctx context.Context, id platform.ID) error { url, err := NewURL(s.Addr, targetIDPath(id)) if err != nil { return err @@ -526,7 +529,7 @@ func (s *ScraperService) RemoveTarget(ctx context.Context, id influxdb.ID) error } // GetTargetByID returns a single target by ID. -func (s *ScraperService) GetTargetByID(ctx context.Context, id influxdb.ID) (*influxdb.ScraperTarget, error) { +func (s *ScraperService) GetTargetByID(ctx context.Context, id platform.ID) (*influxdb.ScraperTarget, error) { url, err := NewURL(s.Addr, targetIDPath(id)) if err != nil { return nil, err @@ -557,7 +560,7 @@ func (s *ScraperService) GetTargetByID(ctx context.Context, id influxdb.ID) (*in return &targetResp.ScraperTarget, nil } -func targetIDPath(id influxdb.ID) string { +func targetIDPath(id platform.ID) string { return path.Join(prefixTargets, id.String()) } @@ -619,7 +622,7 @@ func (h *ScraperHandler) newTargetResponse(ctx context.Context, target influxdb. res.BucketID = bucket.ID res.Links.Bucket = bucketIDPath(bucket.ID) } else { - res.BucketID = influxdb.InvalidID() + res.BucketID = platform.InvalidID() } org, err := h.OrganizationService.FindOrganizationByID(ctx, target.OrgID) @@ -628,16 +631,16 @@ func (h *ScraperHandler) newTargetResponse(ctx context.Context, target influxdb. res.OrgID = org.ID res.Links.Organization = organizationIDPath(org.ID) } else { - res.OrgID = influxdb.InvalidID() + res.OrgID = platform.InvalidID() } return res, nil } -func organizationIDPath(id influxdb.ID) string { +func organizationIDPath(id platform.ID) string { return path.Join(prefixOrganizations, id.String()) } -func bucketIDPath(id influxdb.ID) string { +func bucketIDPath(id platform.ID) string { return path.Join(prefixBuckets, id.String()) } diff --git a/http/scraper_service_test.go b/http/scraper_service_test.go index 545a82a9fbf..231e92f2689 100644 --- a/http/scraper_service_test.go +++ b/http/scraper_service_test.go @@ -10,6 +10,9 @@ import ( "net/http/httptest" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" platcontext "github.com/influxdata/influxdb/v2/context" @@ -73,7 +76,7 @@ func TestService_handleGetScraperTargets(t *testing.T) { name: "get all scraper targets", fields: fields{ OrganizationService: &mock.OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: platformtesting.MustIDBase16("0000000000000211"), Name: "org1", @@ -81,7 +84,7 @@ func TestService_handleGetScraperTargets(t *testing.T) { }, }, BucketService: &mock.BucketService{ - FindBucketByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: platformtesting.MustIDBase16("0000000000000212"), Name: "bucket1", @@ -168,7 +171,7 @@ func TestService_handleGetScraperTargets(t *testing.T) { name: "get all scraper targets when there are none", fields: fields{ OrganizationService: &mock.OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: platformtesting.MustIDBase16("0000000000000211"), Name: "org1", @@ -176,7 +179,7 @@ func TestService_handleGetScraperTargets(t *testing.T) { }, }, BucketService: &mock.BucketService{ - FindBucketByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: platformtesting.MustIDBase16("0000000000000212"), Name: "bucket1", @@ -276,7 +279,7 @@ func TestService_handleGetScraperTarget(t *testing.T) { name: "get a scraper target by id", fields: fields{ OrganizationService: &mock.OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: platformtesting.MustIDBase16("0000000000000211"), Name: "org1", @@ -284,7 +287,7 @@ func TestService_handleGetScraperTarget(t *testing.T) { }, }, BucketService: &mock.BucketService{ - FindBucketByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: platformtesting.MustIDBase16("0000000000000212"), Name: "bucket1", @@ -292,7 +295,7 @@ func TestService_handleGetScraperTarget(t *testing.T) { }, }, ScraperTargetStoreService: &mock.ScraperTargetStoreService{ - GetTargetByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.ScraperTarget, error) { + GetTargetByIDF: func(ctx context.Context, id platform.ID) (*influxdb.ScraperTarget, error) { if id == targetOneID { return &influxdb.ScraperTarget{ ID: targetOneID, @@ -303,8 +306,8 @@ func TestService_handleGetScraperTarget(t *testing.T) { BucketID: platformtesting.MustIDBase16("0000000000000212"), }, nil } - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: "scraper target is not found", } }, @@ -413,7 +416,7 @@ func TestService_handleDeleteScraperTarget(t *testing.T) { name: "delete a scraper target by id", fields: fields{ Service: &mock.ScraperTargetStoreService{ - RemoveTargetF: func(ctx context.Context, id influxdb.ID) error { + RemoveTargetF: func(ctx context.Context, id platform.ID) error { if id == targetOneID { return nil } @@ -433,9 +436,9 @@ func TestService_handleDeleteScraperTarget(t *testing.T) { name: "scraper target not found", fields: fields{ Service: &mock.ScraperTargetStoreService{ - RemoveTargetF: func(ctx context.Context, id influxdb.ID) error { - return &influxdb.Error{ - Code: influxdb.ENotFound, + RemoveTargetF: func(ctx context.Context, id platform.ID) error { + return &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrScraperTargetNotFound, } }, @@ -521,7 +524,7 @@ func TestService_handlePostScraperTarget(t *testing.T) { name: "create a new scraper target", fields: fields{ OrganizationService: &mock.OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: platformtesting.MustIDBase16("0000000000000211"), Name: "org1", @@ -529,7 +532,7 @@ func TestService_handlePostScraperTarget(t *testing.T) { }, }, BucketService: &mock.BucketService{ - FindBucketByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: platformtesting.MustIDBase16("0000000000000212"), Name: "bucket1", @@ -537,7 +540,7 @@ func TestService_handlePostScraperTarget(t *testing.T) { }, }, ScraperTargetStoreService: &mock.ScraperTargetStoreService{ - AddTargetF: func(ctx context.Context, st *influxdb.ScraperTarget, userID influxdb.ID) error { + AddTargetF: func(ctx context.Context, st *influxdb.ScraperTarget, userID platform.ID) error { st.ID = targetOneID return nil }, @@ -650,7 +653,7 @@ func TestService_handlePatchScraperTarget(t *testing.T) { name: "update a scraper target", fields: fields{ OrganizationService: &mock.OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: platformtesting.MustIDBase16("0000000000000211"), Name: "org1", @@ -658,7 +661,7 @@ func TestService_handlePatchScraperTarget(t *testing.T) { }, }, BucketService: &mock.BucketService{ - FindBucketByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: platformtesting.MustIDBase16("0000000000000212"), Name: "bucket1", @@ -666,13 +669,13 @@ func TestService_handlePatchScraperTarget(t *testing.T) { }, }, ScraperTargetStoreService: &mock.ScraperTargetStoreService{ - UpdateTargetF: func(ctx context.Context, t *influxdb.ScraperTarget, userID influxdb.ID) (*influxdb.ScraperTarget, error) { + UpdateTargetF: func(ctx context.Context, t *influxdb.ScraperTarget, userID platform.ID) (*influxdb.ScraperTarget, error) { if t.ID == targetOneID { return t, nil } - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: "scraper target is not found", } }, @@ -718,7 +721,7 @@ func TestService_handlePatchScraperTarget(t *testing.T) { name: "scraper target not found", fields: fields{ OrganizationService: &mock.OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: platformtesting.MustIDBase16("0000000000000211"), Name: "org1", @@ -726,7 +729,7 @@ func TestService_handlePatchScraperTarget(t *testing.T) { }, }, BucketService: &mock.BucketService{ - FindBucketByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: platformtesting.MustIDBase16("0000000000000212"), Name: "bucket1", @@ -734,9 +737,9 @@ func TestService_handlePatchScraperTarget(t *testing.T) { }, }, ScraperTargetStoreService: &mock.ScraperTargetStoreService{ - UpdateTargetF: func(ctx context.Context, upd *influxdb.ScraperTarget, userID influxdb.ID) (*influxdb.ScraperTarget, error) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + UpdateTargetF: func(ctx context.Context, upd *influxdb.ScraperTarget, userID platform.ID) (*influxdb.ScraperTarget, error) { + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrScraperTargetNotFound, } }, @@ -844,7 +847,7 @@ func initScraperService(f platformtesting.TargetFields, t *testing.T) (influxdb. scraperBackend.ScraperStorageService = svc scraperBackend.OrganizationService = tenantService scraperBackend.BucketService = &mock.BucketService{ - FindBucketByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: id, Name: "bucket1", diff --git a/http/session_handler.go b/http/session_handler.go index 62bc2fb7df8..e94253e18b5 100644 --- a/http/session_handler.go +++ b/http/session_handler.go @@ -4,6 +4,8 @@ import ( "context" "net/http" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" platform "github.com/influxdata/influxdb/v2" "go.uber.org/zap" @@ -18,7 +20,7 @@ const ( // the SessionHandler. type SessionBackend struct { log *zap.Logger - platform.HTTPErrorHandler + errors.HTTPErrorHandler PasswordsService platform.PasswordsService SessionService platform.SessionService @@ -40,7 +42,7 @@ func NewSessionBackend(log *zap.Logger, b *APIBackend) *SessionBackend { // SessionHandler represents an HTTP API handler for authorizations. type SessionHandler struct { *httprouter.Router - platform.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger PasswordsService platform.PasswordsService @@ -104,11 +106,11 @@ type signinRequest struct { Password string } -func decodeSigninRequest(ctx context.Context, r *http.Request) (*signinRequest, *platform.Error) { +func decodeSigninRequest(ctx context.Context, r *http.Request) (*signinRequest, *errors.Error) { u, p, ok := r.BasicAuth() if !ok { - return nil, &platform.Error{ - Code: platform.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "invalid basic auth", } } @@ -165,8 +167,8 @@ func encodeCookieSession(w http.ResponseWriter, s *platform.Session) { func decodeCookieSession(ctx context.Context, r *http.Request) (string, error) { c, err := r.Cookie(cookieSessionName) if err != nil { - return "", &platform.Error{ - Code: platform.EInvalid, + return "", &errors.Error{ + Code: errors.EInvalid, Err: err, } } diff --git a/http/session_test.go b/http/session_test.go index affee2757e4..acc257e7fb1 100644 --- a/http/session_test.go +++ b/http/session_test.go @@ -7,6 +7,8 @@ import ( "testing" "time" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" "go.uber.org/zap/zaptest" @@ -53,16 +55,16 @@ func TestSessionHandler_handleSignin(t *testing.T) { SessionService: &mock.SessionService{ CreateSessionFn: func(context.Context, string) (*platform.Session, error) { return &platform.Session{ - ID: platform.ID(0), + ID: platform2.ID(0), Key: "abc123xyz", CreatedAt: time.Date(2018, 9, 26, 0, 0, 0, 0, time.UTC), ExpiresAt: time.Date(2030, 9, 26, 0, 0, 0, 0, time.UTC), - UserID: platform.ID(1), + UserID: platform2.ID(1), }, nil }, }, PasswordsService: &mock.PasswordsService{ - ComparePasswordFn: func(context.Context, platform.ID, string) error { + ComparePasswordFn: func(context.Context, platform2.ID, string) error { return nil }, }, diff --git a/http/source_service.go b/http/source_service.go index 0367952f602..56eeca62fbb 100644 --- a/http/source_service.go +++ b/http/source_service.go @@ -7,6 +7,9 @@ import ( "net/http" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/flux" "github.com/influxdata/flux/csv" "github.com/influxdata/flux/lang" @@ -77,7 +80,7 @@ func newSourcesResponse(srcs []*influxdb.Source) *sourcesResponse { // SourceBackend is all services and associated parameters required to construct // the SourceHandler. type SourceBackend struct { - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger SourceService influxdb.SourceService @@ -102,7 +105,7 @@ func NewSourceBackend(log *zap.Logger, b *APIBackend) *SourceBackend { // SourceHandler is a handler for sources type SourceHandler struct { *httprouter.Router - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger SourceService influxdb.SourceService LabelService influxdb.LabelService @@ -148,7 +151,7 @@ func decodeSourceQueryRequest(r *http.Request) (*query.ProxyRequest, error) { DB string `json:"db"` RP string `json:"rp"` Cluster string `json:"cluster"` - OrganizationID influxdb.ID `json:"organizationID"` + OrganizationID platform.ID `json:"organizationID"` // TODO(desa): support influxql dialect Dialect csv.Dialect `json:"dialect"` }{} @@ -281,7 +284,7 @@ func decodeGetBucketsRequest(r *http.Request) (*getBucketsRequest, error) { req.opts = *opts if orgID := qp.Get("orgID"); orgID != "" { - id, err := influxdb.IDFromString(orgID) + id, err := platform.IDFromString(orgID) if err != nil { return nil, err } @@ -297,7 +300,7 @@ func decodeGetBucketsRequest(r *http.Request) (*getBucketsRequest, error) { } if bucketID := qp.Get("id"); bucketID != "" { - id, err := influxdb.IDFromString(bucketID) + id, err := platform.IDFromString(bucketID) if err != nil { return nil, err } @@ -314,8 +317,8 @@ type bucketResponse struct { } type bucket struct { - ID influxdb.ID `json:"id,omitempty"` - OrgID influxdb.ID `json:"orgID,omitempty"` + ID platform.ID `json:"id,omitempty"` + OrgID platform.ID `json:"orgID,omitempty"` Type string `json:"type"` Description string `json:"description,omitempty"` Name string `json:"name"` @@ -481,20 +484,20 @@ func (h *SourceHandler) handleGetSourceHealth(w http.ResponseWriter, r *http.Req } type getSourceRequest struct { - SourceID influxdb.ID + SourceID platform.ID } func decodeGetSourceRequest(ctx context.Context, r *http.Request) (*getSourceRequest, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -524,20 +527,20 @@ func (h *SourceHandler) handleDeleteSource(w http.ResponseWriter, r *http.Reques } type deleteSourceRequest struct { - SourceID influxdb.ID + SourceID platform.ID } func decodeDeleteSourceRequest(ctx context.Context, r *http.Request) (*deleteSourceRequest, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -605,20 +608,20 @@ func (h *SourceHandler) handlePatchSource(w http.ResponseWriter, r *http.Request type patchSourceRequest struct { Update influxdb.SourceUpdate - SourceID influxdb.ID + SourceID platform.ID } func decodePatchSourceRequest(ctx context.Context, r *http.Request) (*patchSourceRequest, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -640,7 +643,7 @@ type SourceService struct { } // FindSourceByID returns a single source by ID. -func (s *SourceService) FindSourceByID(ctx context.Context, id influxdb.ID) (*influxdb.Source, error) { +func (s *SourceService) FindSourceByID(ctx context.Context, id platform.ID) (*influxdb.Source, error) { var b influxdb.Source err := s.Client. Get(prefixSources, id.String()). @@ -677,7 +680,7 @@ func (s *SourceService) CreateSource(ctx context.Context, b *influxdb.Source) er // UpdateSource updates a single source with changeset. // Returns the new source state after update. -func (s *SourceService) UpdateSource(ctx context.Context, id influxdb.ID, upd influxdb.SourceUpdate) (*influxdb.Source, error) { +func (s *SourceService) UpdateSource(ctx context.Context, id platform.ID, upd influxdb.SourceUpdate) (*influxdb.Source, error) { var b influxdb.Source err := s.Client. PatchJSON(upd, prefixSources, id.String()). @@ -690,7 +693,7 @@ func (s *SourceService) UpdateSource(ctx context.Context, id influxdb.ID, upd in } // DeleteSource removes a source by ID. -func (s *SourceService) DeleteSource(ctx context.Context, id influxdb.ID) error { +func (s *SourceService) DeleteSource(ctx context.Context, id platform.ID) error { return s.Client. Delete(prefixSources, id.String()). StatusFn(func(resp *http.Response) error { diff --git a/http/source_service_test.go b/http/source_service_test.go index 906db83c777..ee5534a8c92 100644 --- a/http/source_service_test.go +++ b/http/source_service_test.go @@ -4,6 +4,8 @@ import ( "reflect" "testing" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" ) @@ -16,16 +18,16 @@ func Test_newSourceResponse(t *testing.T) { { name: "self source returns links to this instance", s: &platform.Source{ - ID: platform.ID(1), - OrganizationID: platform.ID(1), + ID: platform2.ID(1), + OrganizationID: platform2.ID(1), Name: "Hi", Type: platform.SelfSourceType, URL: "/", }, want: &sourceResponse{ Source: &platform.Source{ - ID: platform.ID(1), - OrganizationID: platform.ID(1), + ID: platform2.ID(1), + OrganizationID: platform2.ID(1), Name: "Hi", Type: platform.SelfSourceType, URL: "/", @@ -41,16 +43,16 @@ func Test_newSourceResponse(t *testing.T) { { name: "v1 sources have proxied links", s: &platform.Source{ - ID: platform.ID(1), - OrganizationID: platform.ID(1), + ID: platform2.ID(1), + OrganizationID: platform2.ID(1), Name: "Hi", Type: platform.V1SourceType, URL: "/", }, want: &sourceResponse{ Source: &platform.Source{ - ID: platform.ID(1), - OrganizationID: platform.ID(1), + ID: platform2.ID(1), + OrganizationID: platform2.ID(1), Name: "Hi", Type: platform.V1SourceType, URL: "/", diff --git a/http/swagger.go b/http/swagger.go index e45126081a8..fe37a0e60ef 100644 --- a/http/swagger.go +++ b/http/swagger.go @@ -7,8 +7,9 @@ import ( "net/http" "sync" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/ghodss/yaml" - "github.com/influxdata/influxdb/v2" "go.uber.org/zap" ) @@ -16,7 +17,7 @@ var _ http.Handler = (*swaggerLoader)(nil) // swaggerLoader manages loading the swagger asset and serving it as JSON. type swaggerLoader struct { - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger // Ensure we only call initialize once. @@ -29,7 +30,7 @@ type swaggerLoader struct { loadErr error } -func newSwaggerLoader(log *zap.Logger, h influxdb.HTTPErrorHandler) *swaggerLoader { +func newSwaggerLoader(log *zap.Logger, h errors.HTTPErrorHandler) *swaggerLoader { return &swaggerLoader{ log: log, HTTPErrorHandler: h, @@ -55,10 +56,10 @@ func (s *swaggerLoader) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.once.Do(s.initialize) if s.loadErr != nil { - s.HandleHTTPError(r.Context(), &influxdb.Error{ + s.HandleHTTPError(r.Context(), &errors.Error{ Err: s.loadErr, Msg: "this developer binary not built with assets", - Code: influxdb.EInternal, + Code: errors.EInternal, }, w) return } diff --git a/http/task_service.go b/http/task_service.go index 0e4e63f20b0..5651d509057 100644 --- a/http/task_service.go +++ b/http/task_service.go @@ -11,6 +11,9 @@ import ( "strconv" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" pcontext "github.com/influxdata/influxdb/v2/context" @@ -24,7 +27,7 @@ import ( // TaskBackend is all services and associated parameters required to construct // the TaskHandler. type TaskBackend struct { - influxdb.HTTPErrorHandler + errors2.HTTPErrorHandler log *zap.Logger AlgoWProxy FeatureProxyHandler @@ -56,7 +59,7 @@ func NewTaskBackend(log *zap.Logger, b *APIBackend) *TaskBackend { // TaskHandler represents an HTTP API handler for tasks. type TaskHandler struct { *httprouter.Router - influxdb.HTTPErrorHandler + errors2.HTTPErrorHandler log *zap.Logger TaskService influxdb.TaskService @@ -156,10 +159,10 @@ func NewTaskHandler(log *zap.Logger, b *TaskBackend) *TaskHandler { // Task is a package-specific Task format that preserves the expected format for the API, // where time values are represented as strings type Task struct { - ID influxdb.ID `json:"id"` - OrganizationID influxdb.ID `json:"orgID"` + ID platform.ID `json:"id"` + OrganizationID platform.ID `json:"orgID"` Organization string `json:"org"` - OwnerID influxdb.ID `json:"ownerID"` + OwnerID platform.ID `json:"ownerID"` Name string `json:"name"` Description string `json:"description,omitempty"` Status string `json:"status"` @@ -385,8 +388,8 @@ type runResponse struct { // it uses a pointer to a time.Time instead of a time.Time so that we can pass a nil // value for empty time values type httpRun struct { - ID influxdb.ID `json:"id,omitempty"` - TaskID influxdb.ID `json:"taskID"` + ID platform.ID `json:"id,omitempty"` + TaskID platform.ID `json:"taskID"` Status string `json:"status"` ScheduledFor *time.Time `json:"scheduledFor"` StartedAt *time.Time `json:"startedAt,omitempty"` @@ -457,7 +460,7 @@ type runsResponse struct { Runs []*runResponse `json:"runs"` } -func newRunsResponse(rs []*influxdb.Run, taskID influxdb.ID) runsResponse { +func newRunsResponse(rs []*influxdb.Run, taskID platform.ID) runsResponse { r := runsResponse{ Links: map[string]string{ "self": fmt.Sprintf("/api/v2/tasks/%s/runs", taskID), @@ -477,9 +480,9 @@ func (h *TaskHandler) handleGetTasks(w http.ResponseWriter, r *http.Request) { ctx := r.Context() req, err := decodeGetTasksRequest(ctx, r, h.OrganizationService) if err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, - Code: influxdb.EInvalid, + Code: errors2.EInvalid, Msg: "failed to decode request", } h.HandleHTTPError(ctx, err, w) @@ -507,7 +510,7 @@ func decodeGetTasksRequest(ctx context.Context, r *http.Request, orgs influxdb.O req := &getTasksRequest{} if after := qp.Get("after"); after != "" { - id, err := influxdb.IDFromString(after) + id, err := platform.IDFromString(after) if err != nil { return nil, err } @@ -517,9 +520,9 @@ func decodeGetTasksRequest(ctx context.Context, r *http.Request, orgs influxdb.O if orgName := qp.Get("org"); orgName != "" { o, err := orgs.FindOrganization(ctx, influxdb.OrganizationFilter{Name: &orgName}) if err != nil { - if pErr, ok := err.(*influxdb.Error); ok && pErr != nil { - if kv.IsNotFound(err) || pErr.Code == influxdb.EUnauthorized { - return nil, &influxdb.Error{ + if pErr, ok := err.(*errors2.Error); ok && pErr != nil { + if kv.IsNotFound(err) || pErr.Code == errors2.EUnauthorized { + return nil, &errors2.Error{ Err: errors.New("org not found or unauthorized"), Msg: "org " + orgName + " not found or unauthorized", } @@ -531,7 +534,7 @@ func decodeGetTasksRequest(ctx context.Context, r *http.Request, orgs influxdb.O req.filter.OrganizationID = &o.ID } if oid := qp.Get("orgID"); oid != "" { - orgID, err := influxdb.IDFromString(oid) + orgID, err := platform.IDFromString(oid) if err != nil { return nil, err } @@ -539,7 +542,7 @@ func decodeGetTasksRequest(ctx context.Context, r *http.Request, orgs influxdb.O } if userID := qp.Get("user"); userID != "" { - id, err := influxdb.IDFromString(userID) + id, err := platform.IDFromString(userID) if err != nil { return nil, err } @@ -552,8 +555,8 @@ func decodeGetTasksRequest(ctx context.Context, r *http.Request, orgs influxdb.O return nil, err } if lim < 1 || lim > influxdb.TaskMaxPageSize { - return nil, &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + return nil, &errors2.Error{ + Code: errors2.EUnprocessableEntity, Msg: fmt.Sprintf("limit must be between 1 and %d", influxdb.TaskMaxPageSize), } } @@ -582,9 +585,9 @@ func (h *TaskHandler) handlePostTask(w http.ResponseWriter, r *http.Request) { ctx := r.Context() req, err := decodePostTaskRequest(ctx, r) if err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, - Code: influxdb.EInvalid, + Code: errors2.EInvalid, Msg: "failed to decode request", } h.HandleHTTPError(ctx, err, w) @@ -592,7 +595,7 @@ func (h *TaskHandler) handlePostTask(w http.ResponseWriter, r *http.Request) { } if err := h.populateTaskCreateOrg(ctx, &req.TaskCreate); err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, Msg: "could not identify organization", } @@ -601,8 +604,8 @@ func (h *TaskHandler) handlePostTask(w http.ResponseWriter, r *http.Request) { } if !req.TaskCreate.OrganizationID.Valid() { - err := &influxdb.Error{ - Code: influxdb.EInvalid, + err := &errors2.Error{ + Code: errors2.EInvalid, Msg: "invalid organization id", } h.HandleHTTPError(ctx, err, w) @@ -621,10 +624,10 @@ func (h *TaskHandler) handlePostTask(w http.ResponseWriter, r *http.Request) { } // if the error is not already a influxdb.error then make it into one - if _, ok := err.(*influxdb.Error); !ok { - err = &influxdb.Error{ + if _, ok := err.(*errors2.Error); !ok { + err = &errors2.Error{ Err: err, - Code: influxdb.EInternal, + Code: errors2.EInternal, Msg: "failed to create task", } } @@ -671,9 +674,9 @@ func (h *TaskHandler) handleGetTask(w http.ResponseWriter, r *http.Request) { ctx := r.Context() req, err := decodeGetTaskRequest(ctx, r) if err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, - Code: influxdb.EInvalid, + Code: errors2.EInvalid, Msg: "failed to decode request", } h.HandleHTTPError(ctx, err, w) @@ -682,9 +685,9 @@ func (h *TaskHandler) handleGetTask(w http.ResponseWriter, r *http.Request) { task, err := h.TaskService.FindTaskByID(ctx, req.TaskID) if err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, - Code: influxdb.ENotFound, + Code: errors2.ENotFound, Msg: "failed to find task", } h.HandleHTTPError(ctx, err, w) @@ -693,7 +696,7 @@ func (h *TaskHandler) handleGetTask(w http.ResponseWriter, r *http.Request) { labels, err := h.LabelService.FindResourceLabels(ctx, influxdb.LabelMappingFilter{ResourceID: task.ID, ResourceType: influxdb.TasksResourceType}) if err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, Msg: "failed to find resource labels", } @@ -708,20 +711,20 @@ func (h *TaskHandler) handleGetTask(w http.ResponseWriter, r *http.Request) { } type getTaskRequest struct { - TaskID influxdb.ID + TaskID platform.ID } func decodeGetTaskRequest(ctx context.Context, r *http.Request) (*getTaskRequest, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -737,9 +740,9 @@ func (h *TaskHandler) handleUpdateTask(w http.ResponseWriter, r *http.Request) { ctx := r.Context() req, err := decodeUpdateTaskRequest(ctx, r) if err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, - Code: influxdb.EInvalid, + Code: errors2.EInvalid, Msg: "failed to decode request", } h.HandleHTTPError(ctx, err, w) @@ -747,12 +750,12 @@ func (h *TaskHandler) handleUpdateTask(w http.ResponseWriter, r *http.Request) { } task, err := h.TaskService.UpdateTask(ctx, req.TaskID, req.Update) if err != nil { - err := &influxdb.Error{ + err := &errors2.Error{ Err: err, Msg: "failed to update task", } if err.Err == influxdb.ErrTaskNotFound { - err.Code = influxdb.ENotFound + err.Code = errors2.ENotFound } h.HandleHTTPError(ctx, err, w) return @@ -760,7 +763,7 @@ func (h *TaskHandler) handleUpdateTask(w http.ResponseWriter, r *http.Request) { labels, err := h.LabelService.FindResourceLabels(ctx, influxdb.LabelMappingFilter{ResourceID: task.ID, ResourceType: influxdb.TasksResourceType}) if err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, Msg: "failed to find resource labels", } @@ -776,20 +779,20 @@ func (h *TaskHandler) handleUpdateTask(w http.ResponseWriter, r *http.Request) { type updateTaskRequest struct { Update influxdb.TaskUpdate - TaskID influxdb.ID + TaskID platform.ID } func decodeUpdateTaskRequest(ctx context.Context, r *http.Request) (*updateTaskRequest, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: "you must provide a task ID", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -813,9 +816,9 @@ func (h *TaskHandler) handleDeleteTask(w http.ResponseWriter, r *http.Request) { ctx := r.Context() req, err := decodeDeleteTaskRequest(ctx, r) if err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, - Code: influxdb.EInvalid, + Code: errors2.EInvalid, Msg: "failed to decode request", } h.HandleHTTPError(ctx, err, w) @@ -823,12 +826,12 @@ func (h *TaskHandler) handleDeleteTask(w http.ResponseWriter, r *http.Request) { } if err := h.TaskService.DeleteTask(ctx, req.TaskID); err != nil { - err := &influxdb.Error{ + err := &errors2.Error{ Err: err, Msg: "failed to delete task", } if err.Err == influxdb.ErrTaskNotFound { - err.Code = influxdb.ENotFound + err.Code = errors2.ENotFound } h.HandleHTTPError(ctx, err, w) return @@ -838,20 +841,20 @@ func (h *TaskHandler) handleDeleteTask(w http.ResponseWriter, r *http.Request) { } type deleteTaskRequest struct { - TaskID influxdb.ID + TaskID platform.ID } func decodeDeleteTaskRequest(ctx context.Context, r *http.Request) (*deleteTaskRequest, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: "you must provide a task ID", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -866,9 +869,9 @@ func (h *TaskHandler) handleGetLogs(w http.ResponseWriter, r *http.Request) { req, err := decodeGetLogsRequest(ctx, r) if err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, - Code: influxdb.EInvalid, + Code: errors2.EInvalid, Msg: "failed to decode request", } h.HandleHTTPError(ctx, err, w) @@ -877,9 +880,9 @@ func (h *TaskHandler) handleGetLogs(w http.ResponseWriter, r *http.Request) { auth, err := pcontext.GetAuthorizer(ctx) if err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, - Code: influxdb.EUnauthorized, + Code: errors2.EUnauthorized, Msg: "failed to get authorizer", } h.HandleHTTPError(ctx, err, w) @@ -900,12 +903,12 @@ func (h *TaskHandler) handleGetLogs(w http.ResponseWriter, r *http.Request) { logs, _, err := h.TaskService.FindLogs(ctx, req.filter) if err != nil { - err := &influxdb.Error{ + err := &errors2.Error{ Err: err, Msg: "failed to find task logs", } if err.Err == influxdb.ErrTaskNotFound || err.Err == influxdb.ErrNoRunsFound { - err.Code = influxdb.ENotFound + err.Code = errors2.ENotFound } h.HandleHTTPError(ctx, err, w) return @@ -929,21 +932,21 @@ func decodeGetLogsRequest(ctx context.Context, r *http.Request) (*getLogsRequest params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: "you must provide a task ID", } } req := &getLogsRequest{} - taskID, err := influxdb.IDFromString(id) + taskID, err := platform.IDFromString(id) if err != nil { return nil, err } req.filter.Task = *taskID if runID := params.ByName("rid"); runID != "" { - id, err := influxdb.IDFromString(runID) + id, err := platform.IDFromString(runID) if err != nil { return nil, err } @@ -958,9 +961,9 @@ func (h *TaskHandler) handleGetRuns(w http.ResponseWriter, r *http.Request) { req, err := decodeGetRunsRequest(ctx, r) if err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, - Code: influxdb.EInvalid, + Code: errors2.EInvalid, Msg: "failed to decode request", } h.HandleHTTPError(ctx, err, w) @@ -969,9 +972,9 @@ func (h *TaskHandler) handleGetRuns(w http.ResponseWriter, r *http.Request) { auth, err := pcontext.GetAuthorizer(ctx) if err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, - Code: influxdb.EUnauthorized, + Code: errors2.EUnauthorized, Msg: "failed to get authorizer", } h.HandleHTTPError(ctx, err, w) @@ -992,12 +995,12 @@ func (h *TaskHandler) handleGetRuns(w http.ResponseWriter, r *http.Request) { runs, _, err := h.TaskService.FindRuns(ctx, req.filter) if err != nil { - err := &influxdb.Error{ + err := &errors2.Error{ Err: err, Msg: "failed to find runs", } if err.Err == influxdb.ErrTaskNotFound || err.Err == influxdb.ErrNoRunsFound { - err.Code = influxdb.ENotFound + err.Code = errors2.ENotFound } h.HandleHTTPError(ctx, err, w) return @@ -1017,14 +1020,14 @@ func decodeGetRunsRequest(ctx context.Context, r *http.Request) (*getRunsRequest params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: "you must provide a task ID", } } req := &getRunsRequest{} - taskID, err := influxdb.IDFromString(id) + taskID, err := platform.IDFromString(id) if err != nil { return nil, err } @@ -1033,7 +1036,7 @@ func decodeGetRunsRequest(ctx context.Context, r *http.Request) (*getRunsRequest qp := r.URL.Query() if id := qp.Get("after"); id != "" { - afterID, err := influxdb.IDFromString(id) + afterID, err := platform.IDFromString(id) if err != nil { return nil, err } @@ -1071,8 +1074,8 @@ func decodeGetRunsRequest(ctx context.Context, r *http.Request) (*getRunsRequest } if at != "" && bt != "" && !beforeTime.After(afterTime) { - return nil, &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + return nil, &errors2.Error{ + Code: errors2.EUnprocessableEntity, Msg: "beforeTime must be later than afterTime", } } @@ -1085,9 +1088,9 @@ func (h *TaskHandler) handleForceRun(w http.ResponseWriter, r *http.Request) { req, err := decodeForceRunRequest(ctx, r) if err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, - Code: influxdb.EInvalid, + Code: errors2.EInvalid, Msg: "failed to decode request", } h.HandleHTTPError(ctx, err, w) @@ -1096,12 +1099,12 @@ func (h *TaskHandler) handleForceRun(w http.ResponseWriter, r *http.Request) { run, err := h.TaskService.ForceRun(ctx, req.TaskID, req.Timestamp) if err != nil { - err := &influxdb.Error{ + err := &errors2.Error{ Err: err, Msg: "failed to force run", } if err.Err == influxdb.ErrTaskNotFound { - err.Code = influxdb.ENotFound + err.Code = errors2.ENotFound } h.HandleHTTPError(ctx, err, w) return @@ -1113,7 +1116,7 @@ func (h *TaskHandler) handleForceRun(w http.ResponseWriter, r *http.Request) { } type forceRunRequest struct { - TaskID influxdb.ID + TaskID platform.ID Timestamp int64 } @@ -1121,13 +1124,13 @@ func decodeForceRunRequest(ctx context.Context, r *http.Request) (forceRunReques params := httprouter.ParamsFromContext(ctx) tid := params.ByName("id") if tid == "" { - return forceRunRequest{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return forceRunRequest{}, &errors2.Error{ + Code: errors2.EInvalid, Msg: "you must provide a task ID", } } - var ti influxdb.ID + var ti platform.ID if err := ti.DecodeFromString(tid); err != nil { return forceRunRequest{}, err } @@ -1164,9 +1167,9 @@ func (h *TaskHandler) handleGetRun(w http.ResponseWriter, r *http.Request) { req, err := decodeGetRunRequest(ctx, r) if err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, - Code: influxdb.EInvalid, + Code: errors2.EInvalid, Msg: "failed to decode request", } h.HandleHTTPError(ctx, err, w) @@ -1175,9 +1178,9 @@ func (h *TaskHandler) handleGetRun(w http.ResponseWriter, r *http.Request) { auth, err := pcontext.GetAuthorizer(ctx) if err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, - Code: influxdb.EUnauthorized, + Code: errors2.EUnauthorized, Msg: "failed to get authorizer", } h.HandleHTTPError(ctx, err, w) @@ -1198,12 +1201,12 @@ func (h *TaskHandler) handleGetRun(w http.ResponseWriter, r *http.Request) { run, err := h.TaskService.FindRunByID(ctx, req.TaskID, req.RunID) if err != nil { - err := &influxdb.Error{ + err := &errors2.Error{ Err: err, Msg: "failed to find run", } if err.Err == influxdb.ErrTaskNotFound || err.Err == influxdb.ErrRunNotFound { - err.Code = influxdb.ENotFound + err.Code = errors2.ENotFound } h.HandleHTTPError(ctx, err, w) return @@ -1216,28 +1219,28 @@ func (h *TaskHandler) handleGetRun(w http.ResponseWriter, r *http.Request) { } type getRunRequest struct { - TaskID influxdb.ID - RunID influxdb.ID + TaskID platform.ID + RunID platform.ID } func decodeGetRunRequest(ctx context.Context, r *http.Request) (*getRunRequest, error) { params := httprouter.ParamsFromContext(ctx) tid := params.ByName("id") if tid == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: "you must provide a task ID", } } rid := params.ByName("rid") if rid == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: "you must provide a run ID", } } - var ti, ri influxdb.ID + var ti, ri platform.ID if err := ti.DecodeFromString(tid); err != nil { return nil, err } @@ -1252,32 +1255,32 @@ func decodeGetRunRequest(ctx context.Context, r *http.Request) (*getRunRequest, } type cancelRunRequest struct { - RunID influxdb.ID - TaskID influxdb.ID + RunID platform.ID + TaskID platform.ID } func decodeCancelRunRequest(ctx context.Context, r *http.Request) (*cancelRunRequest, error) { params := httprouter.ParamsFromContext(ctx) rid := params.ByName("rid") if rid == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: "you must provide a run ID", } } tid := params.ByName("id") if tid == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: "you must provide a task ID", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(rid); err != nil { return nil, err } - var t influxdb.ID + var t platform.ID if err := t.DecodeFromString(tid); err != nil { return nil, err } @@ -1293,9 +1296,9 @@ func (h *TaskHandler) handleCancelRun(w http.ResponseWriter, r *http.Request) { req, err := decodeCancelRunRequest(ctx, r) if err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, - Code: influxdb.EInvalid, + Code: errors2.EInvalid, Msg: "failed to decode request", } h.HandleHTTPError(ctx, err, w) @@ -1304,12 +1307,12 @@ func (h *TaskHandler) handleCancelRun(w http.ResponseWriter, r *http.Request) { err = h.TaskService.CancelRun(ctx, req.TaskID, req.RunID) if err != nil { - err := &influxdb.Error{ + err := &errors2.Error{ Err: err, Msg: "failed to cancel run", } if err.Err == influxdb.ErrTaskNotFound || err.Err == influxdb.ErrRunNotFound { - err.Code = influxdb.ENotFound + err.Code = errors2.ENotFound } h.HandleHTTPError(ctx, err, w) return @@ -1321,9 +1324,9 @@ func (h *TaskHandler) handleRetryRun(w http.ResponseWriter, r *http.Request) { req, err := decodeRetryRunRequest(ctx, r) if err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, - Code: influxdb.EInvalid, + Code: errors2.EInvalid, Msg: "failed to decode request", } h.HandleHTTPError(ctx, err, w) @@ -1332,9 +1335,9 @@ func (h *TaskHandler) handleRetryRun(w http.ResponseWriter, r *http.Request) { auth, err := pcontext.GetAuthorizer(ctx) if err != nil { - err = &influxdb.Error{ + err = &errors2.Error{ Err: err, - Code: influxdb.EUnauthorized, + Code: errors2.EUnauthorized, Msg: "failed to get authorizer", } h.HandleHTTPError(ctx, err, w) @@ -1355,12 +1358,12 @@ func (h *TaskHandler) handleRetryRun(w http.ResponseWriter, r *http.Request) { run, err := h.TaskService.RetryRun(ctx, req.TaskID, req.RunID) if err != nil { - err := &influxdb.Error{ + err := &errors2.Error{ Err: err, Msg: "failed to retry run", } if err.Err == influxdb.ErrTaskNotFound || err.Err == influxdb.ErrRunNotFound { - err.Code = influxdb.ENotFound + err.Code = errors2.ENotFound } h.HandleHTTPError(ctx, err, w) return @@ -1372,27 +1375,27 @@ func (h *TaskHandler) handleRetryRun(w http.ResponseWriter, r *http.Request) { } type retryRunRequest struct { - RunID, TaskID influxdb.ID + RunID, TaskID platform.ID } func decodeRetryRunRequest(ctx context.Context, r *http.Request) (*retryRunRequest, error) { params := httprouter.ParamsFromContext(ctx) tid := params.ByName("id") if tid == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: "you must provide a task ID", } } rid := params.ByName("rid") if rid == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: "you must provide a run ID", } } - var ti, ri influxdb.ID + var ti, ri platform.ID if err := ti.DecodeFromString(tid); err != nil { return nil, err } @@ -1435,11 +1438,11 @@ func (h *TaskHandler) populateTaskCreateOrg(ctx context.Context, tc *influxdb.Ta // ensuring that the authorizer on ctx is allowed to view the task and the authorization. // // This method returns a *influxdb.Error, suitable for directly passing to h.HandleHTTPError. -func (h *TaskHandler) getAuthorizationForTask(ctx context.Context, auth influxdb.Authorizer, taskID influxdb.ID) (*influxdb.Authorization, *influxdb.Error) { +func (h *TaskHandler) getAuthorizationForTask(ctx context.Context, auth influxdb.Authorizer, taskID platform.ID) (*influxdb.Authorization, *errors2.Error) { sess, ok := auth.(*influxdb.Session) if !ok { - return nil, &influxdb.Error{ - Code: influxdb.EUnauthorized, + return nil, &errors2.Error{ + Code: errors2.EUnauthorized, Msg: "unable to authorize session", } } @@ -1447,9 +1450,9 @@ func (h *TaskHandler) getAuthorizationForTask(ctx context.Context, auth influxdb // This assumes h.TaskService validates access. t, err := h.TaskService.FindTaskByID(ctx, taskID) if err != nil { - return nil, &influxdb.Error{ + return nil, &errors2.Error{ Err: err, - Code: influxdb.EUnauthorized, + Code: errors2.EUnauthorized, Msg: "task ID unknown or unauthorized", } } @@ -1463,7 +1466,7 @@ type TaskService struct { } // FindTaskByID returns a single task -func (t TaskService) FindTaskByID(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { +func (t TaskService) FindTaskByID(ctx context.Context, id platform.ID) (*influxdb.Task, error) { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -1544,7 +1547,7 @@ func (t TaskService) CreateTask(ctx context.Context, tc influxdb.TaskCreate) (*i } // UpdateTask updates a single task with changeset. -func (t TaskService) UpdateTask(ctx context.Context, id influxdb.ID, upd influxdb.TaskUpdate) (*influxdb.Task, error) { +func (t TaskService) UpdateTask(ctx context.Context, id platform.ID, upd influxdb.TaskUpdate) (*influxdb.Task, error) { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -1560,7 +1563,7 @@ func (t TaskService) UpdateTask(ctx context.Context, id influxdb.ID, upd influxd } // DeleteTask removes a task by ID and purges all associated data and scheduled runs. -func (t TaskService) DeleteTask(ctx context.Context, id influxdb.ID) error { +func (t TaskService) DeleteTask(ctx context.Context, id platform.ID) error { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -1638,7 +1641,7 @@ func (t TaskService) FindRuns(ctx context.Context, filter influxdb.RunFilter) ([ } // FindRunByID returns a single run of a specific task. -func (t TaskService) FindRunByID(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (t TaskService) FindRunByID(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -1649,7 +1652,7 @@ func (t TaskService) FindRunByID(ctx context.Context, taskID, runID influxdb.ID) Do(ctx) if err != nil { - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors2.ErrorCode(err) == errors2.ENotFound { // ErrRunNotFound is expected as part of the FindRunByID contract, // so return that actual error instead of a different error that looks like it. // TODO cleanup backend error implementation @@ -1663,7 +1666,7 @@ func (t TaskService) FindRunByID(ctx context.Context, taskID, runID influxdb.ID) } // RetryRun creates and returns a new run (which is a retry of another run). -func (t TaskService) RetryRun(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (t TaskService) RetryRun(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -1674,7 +1677,7 @@ func (t TaskService) RetryRun(ctx context.Context, taskID, runID influxdb.ID) (* Do(ctx) if err != nil { - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors2.ErrorCode(err) == errors2.ENotFound { // ErrRunNotFound is expected as part of the RetryRun contract, // so return that actual error instead of a different error that looks like it. // TODO cleanup backend task error implementation @@ -1692,7 +1695,7 @@ func (t TaskService) RetryRun(ctx context.Context, taskID, runID influxdb.ID) (* } // ForceRun starts a run manually right now. -func (t TaskService) ForceRun(ctx context.Context, taskID influxdb.ID, scheduledFor int64) (*influxdb.Run, error) { +func (t TaskService) ForceRun(ctx context.Context, taskID platform.ID, scheduledFor int64) (*influxdb.Run, error) { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -1708,7 +1711,7 @@ func (t TaskService) ForceRun(ctx context.Context, taskID influxdb.ID, scheduled Do(ctx) if err != nil { - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors2.ErrorCode(err) == errors2.ENotFound { // ErrRunNotFound is expected as part of the RetryRun contract, // so return that actual error instead of a different error that looks like it. return nil, influxdb.ErrRunNotFound @@ -1725,12 +1728,12 @@ func (t TaskService) ForceRun(ctx context.Context, taskID influxdb.ID, scheduled return convertRun(rs.httpRun), nil } -func cancelPath(taskID, runID influxdb.ID) string { +func cancelPath(taskID, runID platform.ID) string { return path.Join(taskID.String(), runID.String()) } // CancelRun stops a longer running run. -func (t TaskService) CancelRun(ctx context.Context, taskID, runID influxdb.ID) error { +func (t TaskService) CancelRun(ctx context.Context, taskID, runID platform.ID) error { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -1745,14 +1748,14 @@ func (t TaskService) CancelRun(ctx context.Context, taskID, runID influxdb.ID) e return nil } -func taskIDPath(id influxdb.ID) string { +func taskIDPath(id platform.ID) string { return path.Join(prefixTasks, id.String()) } -func taskIDRunsPath(id influxdb.ID) string { +func taskIDRunsPath(id platform.ID) string { return path.Join(prefixTasks, id.String(), "runs") } -func taskIDRunIDPath(taskID, runID influxdb.ID) string { +func taskIDRunIDPath(taskID, runID platform.ID) string { return path.Join(prefixTasks, taskID.String(), "runs", runID.String()) } diff --git a/http/task_service_test.go b/http/task_service_test.go index 330fb945db3..cc3cfaed5c6 100644 --- a/http/task_service_test.go +++ b/http/task_service_test.go @@ -13,6 +13,9 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/authorization" @@ -40,17 +43,17 @@ func NewMockTaskBackend(t *testing.T) *TaskBackend { AuthorizationService: mock.NewAuthorizationService(), TaskService: &mock.TaskService{}, OrganizationService: &mock.OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ID: id, Name: "test"}, nil }, FindOrganizationF: func(ctx context.Context, filter influxdb.OrganizationFilter) (*influxdb.Organization, error) { org := &influxdb.Organization{} if filter.Name != nil { if *filter.Name == "non-existent-org" { - return nil, &influxdb.Error{ + return nil, &errors2.Error{ Err: errors.New("org not found or unauthorized"), Msg: "org " + *filter.Name + " not found or unauthorized", - Code: influxdb.ENotFound, + Code: errors2.ENotFound, } } org.Name = *filter.Name @@ -499,10 +502,10 @@ func TestTaskHandler_handlePostTasks(t *testing.T) { fields: fields{ taskService: &mock.TaskService{ CreateTaskFn: func(ctx context.Context, tc influxdb.TaskCreate) (*influxdb.Task, error) { - return nil, influxdb.NewError( - influxdb.WithErrorErr(errors.New("something went wrong")), - influxdb.WithErrorMsg("something really went wrong"), - influxdb.WithErrorCode(influxdb.EInvalid), + return nil, errors2.NewError( + errors2.WithErrorErr(errors.New("something went wrong")), + errors2.WithErrorMsg("something really went wrong"), + errors2.WithErrorCode(errors2.EInvalid), ) }, }, @@ -591,8 +594,8 @@ func TestTaskHandler_handleGetRun(t *testing.T) { taskService influxdb.TaskService } type args struct { - taskID influxdb.ID - runID influxdb.ID + taskID platform.ID + runID platform.ID } type wants struct { statusCode int @@ -610,7 +613,7 @@ func TestTaskHandler_handleGetRun(t *testing.T) { name: "get a run by id", fields: fields{ taskService: &mock.TaskService{ - FindRunByIDFn: func(ctx context.Context, taskID influxdb.ID, runID influxdb.ID) (*influxdb.Run, error) { + FindRunByIDFn: func(ctx context.Context, taskID platform.ID, runID platform.ID) (*influxdb.Run, error) { scheduledFor, _ := time.Parse(time.RFC3339, "2018-12-01T17:00:13Z") startedAt, _ := time.Parse(time.RFC3339Nano, "2018-12-01T17:00:03.155645Z") finishedAt, _ := time.Parse(time.RFC3339Nano, "2018-12-01T17:00:13.155645Z") @@ -705,7 +708,7 @@ func TestTaskHandler_handleGetRuns(t *testing.T) { taskService influxdb.TaskService } type args struct { - taskID influxdb.ID + taskID platform.ID } type wants struct { statusCode int @@ -730,7 +733,7 @@ func TestTaskHandler_handleGetRuns(t *testing.T) { requestedAt, _ := time.Parse(time.RFC3339, "2018-12-01T17:00:13Z") runs := []*influxdb.Run{ { - ID: influxdb.ID(2), + ID: platform.ID(2), TaskID: f.Task, Status: "success", ScheduledFor: scheduledFor, @@ -844,7 +847,7 @@ func TestTaskHandler_NotFoundStatus(t *testing.T) { // Create a session to associate with the contexts, so authorization checks pass. authz := &influxdb.Authorization{Permissions: influxdb.OperPermissions()} - const taskID, runID = influxdb.ID(0xCCCCCC), influxdb.ID(0xAAAAAA) + const taskID, runID = platform.ID(0xCCCCCC), platform.ID(0xAAAAAA) var ( okTask = []interface{}{taskID} @@ -872,7 +875,7 @@ func TestTaskHandler_NotFoundStatus(t *testing.T) { { name: "get task", svc: &mock.TaskService{ - FindTaskByIDFn: func(_ context.Context, id influxdb.ID) (*influxdb.Task, error) { + FindTaskByIDFn: func(_ context.Context, id platform.ID) (*influxdb.Task, error) { if id == taskID { return &influxdb.Task{ID: taskID, Organization: "o"}, nil } @@ -888,7 +891,7 @@ func TestTaskHandler_NotFoundStatus(t *testing.T) { { name: "update task", svc: &mock.TaskService{ - UpdateTaskFn: func(_ context.Context, id influxdb.ID, _ influxdb.TaskUpdate) (*influxdb.Task, error) { + UpdateTaskFn: func(_ context.Context, id platform.ID, _ influxdb.TaskUpdate) (*influxdb.Task, error) { if id == taskID { return &influxdb.Task{ID: taskID, Organization: "o"}, nil } @@ -905,7 +908,7 @@ func TestTaskHandler_NotFoundStatus(t *testing.T) { { name: "delete task", svc: &mock.TaskService{ - DeleteTaskFn: func(_ context.Context, id influxdb.ID) error { + DeleteTaskFn: func(_ context.Context, id platform.ID) error { if id == taskID { return nil } @@ -988,7 +991,7 @@ func TestTaskHandler_NotFoundStatus(t *testing.T) { { name: "force run", svc: &mock.TaskService{ - ForceRunFn: func(_ context.Context, tid influxdb.ID, _ int64) (*influxdb.Run, error) { + ForceRunFn: func(_ context.Context, tid platform.ID, _ int64) (*influxdb.Run, error) { if tid != taskID { return nil, influxdb.ErrTaskNotFound } @@ -1005,7 +1008,7 @@ func TestTaskHandler_NotFoundStatus(t *testing.T) { { name: "get run", svc: &mock.TaskService{ - FindRunByIDFn: func(_ context.Context, tid, rid influxdb.ID) (*influxdb.Run, error) { + FindRunByIDFn: func(_ context.Context, tid, rid platform.ID) (*influxdb.Run, error) { if tid != taskID { return nil, influxdb.ErrTaskNotFound } @@ -1024,7 +1027,7 @@ func TestTaskHandler_NotFoundStatus(t *testing.T) { { name: "retry run", svc: &mock.TaskService{ - RetryRunFn: func(_ context.Context, tid, rid influxdb.ID) (*influxdb.Run, error) { + RetryRunFn: func(_ context.Context, tid, rid platform.ID) (*influxdb.Run, error) { if tid != taskID { return nil, influxdb.ErrTaskNotFound } @@ -1043,7 +1046,7 @@ func TestTaskHandler_NotFoundStatus(t *testing.T) { { name: "cancel run", svc: &mock.TaskService{ - CancelRunFn: func(_ context.Context, tid, rid influxdb.ID) error { + CancelRunFn: func(_ context.Context, tid, rid platform.ID) error { if tid != taskID { return influxdb.ErrTaskNotFound } @@ -1117,7 +1120,7 @@ func TestService_handlePostTaskLabel(t *testing.T) { } type args struct { labelMapping *influxdb.LabelMapping - taskID influxdb.ID + taskID platform.ID } type wants struct { statusCode int @@ -1135,7 +1138,7 @@ func TestService_handlePostTaskLabel(t *testing.T) { name: "add label to task", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, Name: "label", @@ -1391,8 +1394,8 @@ func TestTaskHandler_Sessions(t *testing.T) { t.Fatal(err) } - const taskID = influxdb.ID(12345) - const runID = influxdb.ID(9876) + const taskID = platform.ID(12345) + const runID = platform.ID(9876) var findRunsCtx context.Context ts := &mock.TaskService{ @@ -1407,7 +1410,7 @@ func TestTaskHandler_Sessions(t *testing.T) { }, 1, nil }, - FindTaskByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + FindTaskByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { if id != taskID { return nil, influxdb.ErrTaskNotFound } @@ -1483,12 +1486,12 @@ func TestTaskHandler_Sessions(t *testing.T) { t.Fatal(err) } - const taskID = influxdb.ID(12345) - const runID = influxdb.ID(9876) + const taskID = platform.ID(12345) + const runID = platform.ID(9876) var findRunByIDCtx context.Context ts := &mock.TaskService{ - FindRunByIDFn: func(ctx context.Context, tid, rid influxdb.ID) (*influxdb.Run, error) { + FindRunByIDFn: func(ctx context.Context, tid, rid platform.ID) (*influxdb.Run, error) { findRunByIDCtx = ctx if tid != taskID { t.Fatalf("expected task ID %v, got %v", taskID, tid) @@ -1500,7 +1503,7 @@ func TestTaskHandler_Sessions(t *testing.T) { return &influxdb.Run{ID: runID, TaskID: taskID}, nil }, - FindTaskByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + FindTaskByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { if id != taskID { return nil, influxdb.ErrTaskNotFound } @@ -1577,8 +1580,8 @@ func TestTaskHandler_Sessions(t *testing.T) { t.Fatal(err) } - const taskID = influxdb.ID(12345) - const runID = influxdb.ID(9876) + const taskID = platform.ID(12345) + const runID = platform.ID(9876) var findLogsCtx context.Context ts := &mock.TaskService{ @@ -1595,7 +1598,7 @@ func TestTaskHandler_Sessions(t *testing.T) { return []*influxdb.Log{&line}, 1, nil }, - FindTaskByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + FindTaskByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { if id != taskID { return nil, influxdb.ErrTaskNotFound } @@ -1672,12 +1675,12 @@ func TestTaskHandler_Sessions(t *testing.T) { t.Fatal(err) } - const taskID = influxdb.ID(12345) - const runID = influxdb.ID(9876) + const taskID = platform.ID(12345) + const runID = platform.ID(9876) var retryRunCtx context.Context ts := &mock.TaskService{ - RetryRunFn: func(ctx context.Context, tid, rid influxdb.ID) (*influxdb.Run, error) { + RetryRunFn: func(ctx context.Context, tid, rid platform.ID) (*influxdb.Run, error) { retryRunCtx = ctx if tid != taskID { t.Fatalf("expected task ID %v, got %v", taskID, tid) @@ -1689,7 +1692,7 @@ func TestTaskHandler_Sessions(t *testing.T) { return &influxdb.Run{ID: 10 * runID, TaskID: taskID}, nil }, - FindTaskByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + FindTaskByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { if id != taskID { return nil, influxdb.ErrTaskNotFound } diff --git a/http/telegraf.go b/http/telegraf.go index 43c8b483a5d..fe4b14ea2da 100644 --- a/http/telegraf.go +++ b/http/telegraf.go @@ -7,6 +7,9 @@ import ( "net/http" "strings" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/golang/gddo/httputil" "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" @@ -19,7 +22,7 @@ import ( // TelegrafBackend is all services and associated parameters required to construct // the TelegrafHandler. type TelegrafBackend struct { - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger TelegrafService influxdb.TelegrafConfigStore @@ -46,7 +49,7 @@ func NewTelegrafBackend(log *zap.Logger, b *APIBackend) *TelegrafBackend { // TelegrafHandler is the handler for the telegraf service type TelegrafHandler struct { *httprouter.Router - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger TelegrafService influxdb.TelegrafConfigStore @@ -198,12 +201,12 @@ func newTelegrafResponses(ctx context.Context, tcs []*influxdb.TelegrafConfig, l return resp } -func decodeGetTelegrafRequest(ctx context.Context) (i influxdb.ID, err error) { +func decodeGetTelegrafRequest(ctx context.Context) (i platform.ID, err error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return i, &influxdb.Error{ - Code: influxdb.EInvalid, + return i, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } @@ -281,10 +284,10 @@ func decodeTelegrafConfigFilter(ctx context.Context, r *http.Request) (*influxdb q := r.URL.Query() if orgIDStr := q.Get("orgID"); orgIDStr != "" { - orgID, err := influxdb.IDFromString(orgIDStr) + orgID, err := platform.IDFromString(orgIDStr) if err != nil { - return f, &influxdb.Error{ - Code: influxdb.EInvalid, + return f, &errors.Error{ + Code: errors.EInvalid, Msg: "orgID is invalid", Err: err, } @@ -334,12 +337,12 @@ func decodePutTelegrafRequest(ctx context.Context, r *http.Request) (*influxdb.T params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - i := new(influxdb.ID) + i := new(platform.ID) if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -419,7 +422,7 @@ func NewTelegrafService(httpClient *httpc.Client) *TelegrafService { var _ influxdb.TelegrafConfigStore = (*TelegrafService)(nil) // FindTelegrafConfigByID returns a single telegraf config by ID. -func (s *TelegrafService) FindTelegrafConfigByID(ctx context.Context, id influxdb.ID) (*influxdb.TelegrafConfig, error) { +func (s *TelegrafService) FindTelegrafConfigByID(ctx context.Context, id platform.ID) (*influxdb.TelegrafConfig, error) { var cfg influxdb.TelegrafConfig err := s.client. Get(prefixTelegraf, id.String()). @@ -459,7 +462,7 @@ func (s *TelegrafService) FindTelegrafConfigs(ctx context.Context, f influxdb.Te } // CreateTelegrafConfig creates a new telegraf config and sets b.ID with the new identifier. -func (s *TelegrafService) CreateTelegrafConfig(ctx context.Context, tc *influxdb.TelegrafConfig, userID influxdb.ID) error { +func (s *TelegrafService) CreateTelegrafConfig(ctx context.Context, tc *influxdb.TelegrafConfig, userID platform.ID) error { var teleResp influxdb.TelegrafConfig err := s.client. PostJSON(tc, prefixTelegraf). @@ -474,7 +477,7 @@ func (s *TelegrafService) CreateTelegrafConfig(ctx context.Context, tc *influxdb // UpdateTelegrafConfig updates a single telegraf config. // Returns the new telegraf config after update. -func (s *TelegrafService) UpdateTelegrafConfig(ctx context.Context, id influxdb.ID, tc *influxdb.TelegrafConfig, userID influxdb.ID) (*influxdb.TelegrafConfig, error) { +func (s *TelegrafService) UpdateTelegrafConfig(ctx context.Context, id platform.ID, tc *influxdb.TelegrafConfig, userID platform.ID) (*influxdb.TelegrafConfig, error) { var teleResp influxdb.TelegrafConfig err := s.client. PutJSON(tc, prefixTelegraf, id.String()). @@ -487,7 +490,7 @@ func (s *TelegrafService) UpdateTelegrafConfig(ctx context.Context, id influxdb. } // DeleteTelegrafConfig removes a telegraf config by ID. -func (s *TelegrafService) DeleteTelegrafConfig(ctx context.Context, id influxdb.ID) error { +func (s *TelegrafService) DeleteTelegrafConfig(ctx context.Context, id platform.ID) error { return s.client. Delete(prefixTelegraf, id.String()). Do(ctx) diff --git a/http/telegraf_test.go b/http/telegraf_test.go index 81933c235bb..8b63d7e00be 100644 --- a/http/telegraf_test.go +++ b/http/telegraf_test.go @@ -10,6 +10,8 @@ import ( "strings" "testing" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" "go.uber.org/zap/zaptest" @@ -45,11 +47,11 @@ func TestTelegrafHandler_handleGetTelegrafs(t *testing.T) { r: httptest.NewRequest("GET", "http://any.url/api/v2/telegrafs?orgID=0000000000000002", nil), svc: &mock.TelegrafConfigStore{ FindTelegrafConfigsF: func(ctx context.Context, filter platform.TelegrafConfigFilter, opt ...platform.FindOptions) ([]*platform.TelegrafConfig, int, error) { - if filter.OrgID != nil && *filter.OrgID == platform.ID(2) { + if filter.OrgID != nil && *filter.OrgID == platform2.ID(2) { return []*platform.TelegrafConfig{ { - ID: platform.ID(1), - OrgID: platform.ID(2), + ID: platform2.ID(1), + OrgID: platform2.ID(2), Name: "tc1", Description: "", Config: "[[inputs.cpu]]\n", @@ -90,8 +92,8 @@ func TestTelegrafHandler_handleGetTelegrafs(t *testing.T) { if filter.Organization != nil && *filter.Organization == "tc1" { return []*platform.TelegrafConfig{ { - ID: platform.ID(1), - OrgID: platform.ID(2), + ID: platform2.ID(1), + OrgID: platform2.ID(2), Name: "tc1", Description: "", Config: "[[inputs.cpu]]\n", @@ -131,8 +133,8 @@ func TestTelegrafHandler_handleGetTelegrafs(t *testing.T) { FindTelegrafConfigsF: func(ctx context.Context, filter platform.TelegrafConfigFilter, opt ...platform.FindOptions) ([]*platform.TelegrafConfig, int, error) { return []*platform.TelegrafConfig{ { - ID: platform.ID(1), - OrgID: platform.ID(2), + ID: platform2.ID(1), + OrgID: platform2.ID(2), Name: "my config", Description: "my description", Config: "[[inputs.cpu]]\n[[outputs.influxdb_v2]]\n", @@ -212,10 +214,10 @@ func TestTelegrafHandler_handleGetTelegraf(t *testing.T) { r: httptest.NewRequest("GET", "http://any.url/api/v2/telegrafs/0000000000000001", nil), acceptHeader: "application/json", svc: &mock.TelegrafConfigStore{ - FindTelegrafConfigByIDF: func(ctx context.Context, id platform.ID) (*platform.TelegrafConfig, error) { + FindTelegrafConfigByIDF: func(ctx context.Context, id platform2.ID) (*platform.TelegrafConfig, error) { return &platform.TelegrafConfig{ - ID: platform.ID(1), - OrgID: platform.ID(2), + ID: platform2.ID(1), + OrgID: platform2.ID(2), Name: "my config", Description: "", Config: "[[inputs.cpu]]\n[[outputs.influxdb_v2]]\n", @@ -245,10 +247,10 @@ func TestTelegrafHandler_handleGetTelegraf(t *testing.T) { r: httptest.NewRequest("GET", "http://any.url/api/v2/telegrafs/0000000000000001", nil), acceptHeader: "application/json, text/plain, */*", svc: &mock.TelegrafConfigStore{ - FindTelegrafConfigByIDF: func(ctx context.Context, id platform.ID) (*platform.TelegrafConfig, error) { + FindTelegrafConfigByIDF: func(ctx context.Context, id platform2.ID) (*platform.TelegrafConfig, error) { return &platform.TelegrafConfig{ - ID: platform.ID(1), - OrgID: platform.ID(2), + ID: platform2.ID(1), + OrgID: platform2.ID(2), Name: "my config", Description: "", Config: "[[inputs.cpu]]\n[[outputs.influxdb_v2]]\n", @@ -278,10 +280,10 @@ func TestTelegrafHandler_handleGetTelegraf(t *testing.T) { r: httptest.NewRequest("GET", "http://any.url/api/v2/telegrafs/0000000000000001", nil), acceptHeader: "application/toml", svc: &mock.TelegrafConfigStore{ - FindTelegrafConfigByIDF: func(ctx context.Context, id platform.ID) (*platform.TelegrafConfig, error) { + FindTelegrafConfigByIDF: func(ctx context.Context, id platform2.ID) (*platform.TelegrafConfig, error) { return &platform.TelegrafConfig{ - ID: platform.ID(1), - OrgID: platform.ID(2), + ID: platform2.ID(1), + OrgID: platform2.ID(2), Name: "my config", Config: `# Configuration for telegraf agent [agent] @@ -455,10 +457,10 @@ func TestTelegrafHandler_handleGetTelegraf(t *testing.T) { name: "return TOML telegraf config with no accept header", r: httptest.NewRequest("GET", "http://any.url/api/v2/telegrafs/0000000000000001", nil), svc: &mock.TelegrafConfigStore{ - FindTelegrafConfigByIDF: func(ctx context.Context, id platform.ID) (*platform.TelegrafConfig, error) { + FindTelegrafConfigByIDF: func(ctx context.Context, id platform2.ID) (*platform.TelegrafConfig, error) { return &platform.TelegrafConfig{ - ID: platform.ID(1), - OrgID: platform.ID(2), + ID: platform2.ID(1), + OrgID: platform2.ID(2), Config: `# Configuration for telegraf agent [agent] ## Default data collection interval for all inputs @@ -632,10 +634,10 @@ func TestTelegrafHandler_handleGetTelegraf(t *testing.T) { r: httptest.NewRequest("GET", "http://any.url/api/v2/telegrafs/0000000000000001", nil), acceptHeader: "application/octet-stream", svc: &mock.TelegrafConfigStore{ - FindTelegrafConfigByIDF: func(ctx context.Context, id platform.ID) (*platform.TelegrafConfig, error) { + FindTelegrafConfigByIDF: func(ctx context.Context, id platform2.ID) (*platform.TelegrafConfig, error) { return &platform.TelegrafConfig{ - ID: platform.ID(1), - OrgID: platform.ID(2), + ID: platform2.ID(1), + OrgID: platform2.ID(2), Name: "my config", Config: `# Configuration for telegraf agent [agent] @@ -853,8 +855,8 @@ func Test_newTelegrafResponses(t *testing.T) { args: args{ tcs: []*platform.TelegrafConfig{ { - ID: platform.ID(1), - OrgID: platform.ID(2), + ID: platform2.ID(1), + OrgID: platform2.ID(2), Name: "my config", Description: "", Config: "[[inputs.cpu]]\n[[outputs.influxdb_v2]]\n", @@ -907,8 +909,8 @@ func Test_newTelegrafResponse(t *testing.T) { { args: args{ tc: &platform.TelegrafConfig{ - ID: platform.ID(1), - OrgID: platform.ID(2), + ID: platform2.ID(1), + OrgID: platform2.ID(2), Name: "my config", Description: "my description", Config: "[[inputs.cpu]]\n[[outputs.influxdb_v2]]\n", diff --git a/http/user_resource_mapping_service.go b/http/user_resource_mapping_service.go index 9dab545c190..b270311c738 100644 --- a/http/user_resource_mapping_service.go +++ b/http/user_resource_mapping_service.go @@ -7,6 +7,9 @@ import ( "net/http" "path" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/pkg/httpc" @@ -47,7 +50,7 @@ func newResourceUsersResponse(opts influxdb.FindOptions, f influxdb.UserResource // MemberBackend is all services and associated parameters required to construct // member handler. type MemberBackend struct { - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger ResourceType influxdb.ResourceType @@ -94,21 +97,21 @@ func newPostMemberHandler(b MemberBackend) http.HandlerFunc { } type postMemberRequest struct { - MemberID influxdb.ID - ResourceID influxdb.ID + MemberID platform.ID + ResourceID platform.ID } func decodePostMemberRequest(ctx context.Context, r *http.Request) (*postMemberRequest, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var rid influxdb.ID + var rid platform.ID if err := rid.DecodeFromString(id); err != nil { return nil, err } @@ -119,8 +122,8 @@ func decodePostMemberRequest(ctx context.Context, r *http.Request) (*postMemberR } if !u.ID.Valid() { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "user id missing or invalid", } } @@ -177,21 +180,21 @@ func newGetMembersHandler(b MemberBackend) http.HandlerFunc { } type getMembersRequest struct { - MemberID influxdb.ID - ResourceID influxdb.ID + MemberID platform.ID + ResourceID platform.ID } func decodeGetMembersRequest(ctx context.Context, r *http.Request) (*getMembersRequest, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -224,34 +227,34 @@ func newDeleteMemberHandler(b MemberBackend) http.HandlerFunc { } type deleteMemberRequest struct { - MemberID influxdb.ID - ResourceID influxdb.ID + MemberID platform.ID + ResourceID platform.ID } func decodeDeleteMemberRequest(ctx context.Context, r *http.Request) (*deleteMemberRequest, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing resource id", } } - var rid influxdb.ID + var rid platform.ID if err := rid.DecodeFromString(id); err != nil { return nil, err } id = params.ByName("userID") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing member id", } } - var mid influxdb.ID + var mid platform.ID if err := mid.DecodeFromString(id); err != nil { return nil, err } @@ -304,7 +307,7 @@ func (s *UserResourceMappingService) CreateUserResourceMapping(ctx context.Conte } // DeleteUserResourceMapping will delete user resource mapping based in criteria. -func (s *UserResourceMappingService) DeleteUserResourceMapping(ctx context.Context, resourceID influxdb.ID, userID influxdb.ID) error { +func (s *UserResourceMappingService) DeleteUserResourceMapping(ctx context.Context, resourceID platform.ID, userID platform.ID) error { urlPath := resourceIDUserPath(influxdb.OrgsResourceType, resourceID, influxdb.Member, userID) return s.Client. Delete(urlPath). @@ -366,17 +369,17 @@ func (s *SpecificURMSvc) CreateUserResourceMapping(ctx context.Context, m *influ } // DeleteUserResourceMapping will delete user resource mapping based in criteria. -func (s *SpecificURMSvc) DeleteUserResourceMapping(ctx context.Context, resourceID influxdb.ID, userID influxdb.ID) error { +func (s *SpecificURMSvc) DeleteUserResourceMapping(ctx context.Context, resourceID platform.ID, userID platform.ID) error { urlPath := resourceIDUserPath(s.rt, resourceID, s.ut, userID) return s.Client. Delete(urlPath). Do(ctx) } -func resourceIDPath(resourceType influxdb.ResourceType, resourceID influxdb.ID, p string) string { +func resourceIDPath(resourceType influxdb.ResourceType, resourceID platform.ID, p string) string { return path.Join("/api/v2/", string(resourceType), resourceID.String(), p) } -func resourceIDUserPath(resourceType influxdb.ResourceType, resourceID influxdb.ID, userType influxdb.UserType, userID influxdb.ID) string { +func resourceIDUserPath(resourceType influxdb.ResourceType, resourceID platform.ID, userType influxdb.UserType, userID platform.ID) string { return path.Join("/api/v2/", string(resourceType), resourceID.String(), string(userType)+"s", userID.String()) } diff --git a/http/user_resource_mapping_test.go b/http/user_resource_mapping_test.go index 879cc2f70d4..0e9a9b85a53 100644 --- a/http/user_resource_mapping_test.go +++ b/http/user_resource_mapping_test.go @@ -10,6 +10,8 @@ import ( "net/http/httptest" "testing" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/httprouter" platform "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" @@ -41,7 +43,7 @@ func TestUserResourceMappingService_GetMembersHandler(t *testing.T) { name: "get members", fields: fields{ userService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id platform.ID) (*platform.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform2.ID) (*platform.User, error) { return &platform.User{ID: id, Name: fmt.Sprintf("user%s", id), Status: platform.Active}, nil }, }, @@ -107,7 +109,7 @@ func TestUserResourceMappingService_GetMembersHandler(t *testing.T) { name: "get owners", fields: fields{ userService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id platform.ID) (*platform.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform2.ID) (*platform.User, error) { return &platform.User{ID: id, Name: fmt.Sprintf("user%s", id), Status: platform.Active}, nil }, }, @@ -249,7 +251,7 @@ func TestUserResourceMappingService_PostMembersHandler(t *testing.T) { name: "post members", fields: fields{ userService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id platform.ID) (*platform.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform2.ID) (*platform.User, error) { return &platform.User{ID: id, Name: fmt.Sprintf("user%s", id), Status: platform.Active}, nil }, }, @@ -289,7 +291,7 @@ func TestUserResourceMappingService_PostMembersHandler(t *testing.T) { name: "post owners", fields: fields{ userService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id platform.ID) (*platform.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform2.ID) (*platform.User, error) { return &platform.User{ID: id, Name: fmt.Sprintf("user%s", id), Status: platform.Active}, nil }, }, diff --git a/http/user_service.go b/http/user_service.go index ed510d35dfa..4da36850824 100644 --- a/http/user_service.go +++ b/http/user_service.go @@ -6,6 +6,9 @@ import ( "fmt" "net/http" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" icontext "github.com/influxdata/influxdb/v2/context" @@ -16,7 +19,7 @@ import ( // UserBackend is all services and associated parameters required to construct // the UserHandler. type UserBackend struct { - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger UserService influxdb.UserService UserOperationLogService influxdb.UserOperationLogService @@ -37,7 +40,7 @@ func NewUserBackend(log *zap.Logger, b *APIBackend) *UserBackend { // UserHandler represents an HTTP API handler for users. type UserHandler struct { *httprouter.Router - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger UserService influxdb.UserService UserOperationLogService influxdb.UserOperationLogService @@ -90,17 +93,17 @@ func (h *UserHandler) handlePostUserPassword(w http.ResponseWriter, r *http.Requ var body passwordSetRequest err := json.NewDecoder(r.Body).Decode(&body) if err != nil { - h.HandleHTTPError(r.Context(), &influxdb.Error{ - Code: influxdb.EInvalid, + h.HandleHTTPError(r.Context(), &errors.Error{ + Code: errors.EInvalid, Err: err, }, w) return } params := httprouter.ParamsFromContext(r.Context()) - userID, err := influxdb.IDFromString(params.ByName("id")) + userID, err := platform.IDFromString(params.ByName("id")) if err != nil { - h.HandleHTTPError(r.Context(), &influxdb.Error{ + h.HandleHTTPError(r.Context(), &errors.Error{ Msg: "invalid user ID provided in route", }, w) return @@ -122,9 +125,9 @@ func (h *UserHandler) putPassword(ctx context.Context, w http.ResponseWriter, r } params := httprouter.ParamsFromContext(r.Context()) - userID, err := influxdb.IDFromString(params.ByName("id")) + userID, err := platform.IDFromString(params.ByName("id")) if err != nil { - h.HandleHTTPError(r.Context(), &influxdb.Error{ + h.HandleHTTPError(r.Context(), &errors.Error{ Msg: "invalid user ID provided in route", }, w) return @@ -168,8 +171,8 @@ func decodePasswordResetRequest(r *http.Request) (*passwordResetRequest, error) pr := new(passwordResetRequestBody) err := json.NewDecoder(r.Body).Decode(pr) if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -267,20 +270,20 @@ func (h *UserHandler) handleGetUser(w http.ResponseWriter, r *http.Request) { } type getUserRequest struct { - UserID influxdb.ID + UserID platform.ID } func decodeGetUserRequest(ctx context.Context, r *http.Request) (*getUserRequest, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -311,20 +314,20 @@ func (h *UserHandler) handleDeleteUser(w http.ResponseWriter, r *http.Request) { } type deleteUserRequest struct { - UserID influxdb.ID + UserID platform.ID } func decodeDeleteUserRequest(ctx context.Context, r *http.Request) (*deleteUserRequest, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -408,7 +411,7 @@ func decodeGetUsersRequest(ctx context.Context, r *http.Request) (*getUsersReque req := &getUsersRequest{} if userID := qp.Get("id"); userID != "" { - id, err := influxdb.IDFromString(userID) + id, err := platform.IDFromString(userID) if err != nil { return nil, err } @@ -446,20 +449,20 @@ func (h *UserHandler) handlePatchUser(w http.ResponseWriter, r *http.Request) { type patchUserRequest struct { Update influxdb.UserUpdate - UserID influxdb.ID + UserID platform.ID } func decodePatchUserRequest(ctx context.Context, r *http.Request) (*patchUserRequest, error) { params := httprouter.ParamsFromContext(ctx) id := params.ByName("id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -487,7 +490,7 @@ type UserService struct { } // FindMe returns user information about the owner of the token -func (s *UserService) FindMe(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { +func (s *UserService) FindMe(ctx context.Context, id platform.ID) (*influxdb.User, error) { var res UserResponse err := s.Client. Get(prefixMe). @@ -500,7 +503,7 @@ func (s *UserService) FindMe(ctx context.Context, id influxdb.ID) (*influxdb.Use } // FindUserByID returns a single user by ID. -func (s *UserService) FindUserByID(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { +func (s *UserService) FindUserByID(ctx context.Context, id platform.ID) (*influxdb.User, error) { var res UserResponse err := s.Client. Get(prefixUsers, id.String()). @@ -515,22 +518,22 @@ func (s *UserService) FindUserByID(ctx context.Context, id influxdb.ID) (*influx // FindUser returns the first user that matches filter. func (s *UserService) FindUser(ctx context.Context, filter influxdb.UserFilter) (*influxdb.User, error) { if filter.ID == nil && filter.Name == nil { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: "user not found", } } users, n, err := s.FindUsers(ctx, filter) if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Op: s.OpPrefix + influxdb.OpFindUser, Err: err, } } if n == 0 { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Op: s.OpPrefix + influxdb.OpFindUser, Msg: "no results found", } @@ -574,7 +577,7 @@ func (s *UserService) CreateUser(ctx context.Context, u *influxdb.User) error { // UpdateUser updates a single user with changeset. // Returns the new user state after update. -func (s *UserService) UpdateUser(ctx context.Context, id influxdb.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { +func (s *UserService) UpdateUser(ctx context.Context, id platform.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { var res UserResponse err := s.Client. PatchJSON(upd, prefixUsers, id.String()). @@ -587,7 +590,7 @@ func (s *UserService) UpdateUser(ctx context.Context, id influxdb.ID, upd influx } // DeleteUser removes a user by ID. -func (s *UserService) DeleteUser(ctx context.Context, id influxdb.ID) error { +func (s *UserService) DeleteUser(ctx context.Context, id platform.ID) error { return s.Client. Delete(prefixUsers, id.String()). StatusFn(func(resp *http.Response) error { @@ -596,9 +599,9 @@ func (s *UserService) DeleteUser(ctx context.Context, id influxdb.ID) error { Do(ctx) } -func (s *UserService) FindPermissionForUser(ctx context.Context, uid influxdb.ID) (influxdb.PermissionSet, error) { - return nil, &influxdb.Error{ - Code: influxdb.EInternal, +func (s *UserService) FindPermissionForUser(ctx context.Context, uid platform.ID) (influxdb.PermissionSet, error) { + return nil, &errors.Error{ + Code: errors.EInternal, Msg: "not implemented", } } @@ -611,7 +614,7 @@ type PasswordService struct { var _ influxdb.PasswordsService = (*PasswordService)(nil) // SetPassword sets the user's password. -func (s *PasswordService) SetPassword(ctx context.Context, userID influxdb.ID, password string) error { +func (s *PasswordService) SetPassword(ctx context.Context, userID platform.ID, password string) error { return s.Client. PostJSON(passwordSetRequest{ Password: password, @@ -620,12 +623,12 @@ func (s *PasswordService) SetPassword(ctx context.Context, userID influxdb.ID, p } // ComparePassword compares the user new password with existing. Note: is not implemented. -func (s *PasswordService) ComparePassword(ctx context.Context, userID influxdb.ID, password string) error { +func (s *PasswordService) ComparePassword(ctx context.Context, userID platform.ID, password string) error { panic("not implemented") } // CompareAndSetPassword compares the old and new password and submits the new password if possible. // Note: is not implemented. -func (s *PasswordService) CompareAndSetPassword(ctx context.Context, userID influxdb.ID, old string, new string) error { +func (s *PasswordService) CompareAndSetPassword(ctx context.Context, userID platform.ID, old string, new string) error { panic("not implemented") } diff --git a/http/user_test.go b/http/user_test.go index 12777ae0835..8c586e9b444 100644 --- a/http/user_test.go +++ b/http/user_test.go @@ -8,6 +8,8 @@ import ( "path" "testing" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" kithttp "github.com/influxdata/influxdb/v2/kit/transport/http" "github.com/influxdata/influxdb/v2/mock" @@ -70,8 +72,8 @@ func TestUserHandler_SettingPassword(t *testing.T) { be := NewMockUserBackend(t) fakePassSVC := mock.NewPasswordsService() - userID := platform.ID(1) - fakePassSVC.SetPasswordFn = func(_ context.Context, id platform.ID, newPass string) error { + userID := platform2.ID(1) + fakePassSVC.SetPasswordFn = func(_ context.Context, id platform2.ID, newPass string) error { if id != userID { return errors.New("unexpected id: " + id.String()) } diff --git a/http/variable_service.go b/http/variable_service.go index a78635b4723..7e18c4d8c04 100644 --- a/http/variable_service.go +++ b/http/variable_service.go @@ -7,6 +7,9 @@ import ( "net/http" "strings" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/pkg/httpc" @@ -20,7 +23,7 @@ const ( // VariableBackend is all services and associated parameters required to construct // the VariableHandler. type VariableBackend struct { - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger VariableService influxdb.VariableService LabelService influxdb.LabelService @@ -40,7 +43,7 @@ func NewVariableBackend(log *zap.Logger, b *APIBackend) *VariableBackend { type VariableHandler struct { *httprouter.Router - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger VariableService influxdb.VariableService @@ -126,7 +129,7 @@ func decodeGetVariablesRequest(ctx context.Context, r *http.Request) (*getVariab } qp := r.URL.Query() if orgID := qp.Get("orgID"); orgID != "" { - id, err := influxdb.IDFromString(orgID) + id, err := platform.IDFromString(orgID) if err != nil { return nil, err } @@ -150,8 +153,8 @@ func (h *VariableHandler) handleGetVariables(w http.ResponseWriter, r *http.Requ variables, err := h.VariableService.FindVariables(ctx, req.filter, req.opts) if err != nil { - h.HandleHTTPError(ctx, &influxdb.Error{ - Code: influxdb.EInternal, + h.HandleHTTPError(ctx, &errors.Error{ + Code: errors.EInternal, Msg: "could not read variables", Err: err, }, w) @@ -165,19 +168,19 @@ func (h *VariableHandler) handleGetVariables(w http.ResponseWriter, r *http.Requ } } -func requestVariableID(ctx context.Context) (influxdb.ID, error) { +func requestVariableID(ctx context.Context) (platform.ID, error) { params := httprouter.ParamsFromContext(ctx) urlID := params.ByName("id") if urlID == "" { - return influxdb.InvalidID(), &influxdb.Error{ - Code: influxdb.EInvalid, + return platform.InvalidID(), &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - id, err := influxdb.IDFromString(urlID) + id, err := platform.IDFromString(urlID) if err != nil { - return influxdb.InvalidID(), err + return platform.InvalidID(), err } return *id, nil @@ -272,8 +275,8 @@ func decodePostVariableRequest(r *http.Request) (*postVariableRequest, error) { err := json.NewDecoder(r.Body).Decode(m) if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: err.Error(), } } @@ -283,8 +286,8 @@ func decodePostVariableRequest(r *http.Request) (*postVariableRequest, error) { } if err := req.Valid(); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: err.Error(), } } @@ -320,7 +323,7 @@ func (h *VariableHandler) handlePatchVariable(w http.ResponseWriter, r *http.Req } type patchVariableRequest struct { - id influxdb.ID + id platform.ID variableUpdate *influxdb.VariableUpdate } @@ -333,8 +336,8 @@ func decodePatchVariableRequest(ctx context.Context, r *http.Request) (*patchVar err := json.NewDecoder(r.Body).Decode(u) if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: err.Error(), } } @@ -350,8 +353,8 @@ func decodePatchVariableRequest(ctx context.Context, r *http.Request) (*patchVar } if err := req.Valid(); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: err.Error(), } } @@ -390,7 +393,7 @@ func (h *VariableHandler) handlePutVariable(w http.ResponseWriter, r *http.Reque } type putVariableRequest struct { - id influxdb.ID + id platform.ID variable *influxdb.Variable } @@ -403,8 +406,8 @@ func decodePutVariableRequest(ctx context.Context, r *http.Request) (*putVariabl err := json.NewDecoder(r.Body).Decode(m) if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -420,8 +423,8 @@ func decodePutVariableRequest(ctx context.Context, r *http.Request) (*putVariabl } if err := req.Valid(); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -452,7 +455,7 @@ type VariableService struct { } // FindVariableByID finds a single variable from the store by its ID -func (s *VariableService) FindVariableByID(ctx context.Context, id influxdb.ID) (*influxdb.Variable, error) { +func (s *VariableService) FindVariableByID(ctx context.Context, id platform.ID) (*influxdb.Variable, error) { var mr variableResponse err := s.Client. Get(prefixVariables, id.String()). @@ -496,8 +499,8 @@ func (s *VariableService) FindVariables(ctx context.Context, filter influxdb.Var func (s *VariableService) CreateVariable(ctx context.Context, m *influxdb.Variable) error { m.Name = strings.TrimSpace(m.Name) if err := m.Valid(); err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -509,7 +512,7 @@ func (s *VariableService) CreateVariable(ctx context.Context, m *influxdb.Variab } // UpdateVariable updates a single variable with a changeset -func (s *VariableService) UpdateVariable(ctx context.Context, id influxdb.ID, update *influxdb.VariableUpdate) (*influxdb.Variable, error) { +func (s *VariableService) UpdateVariable(ctx context.Context, id platform.ID, update *influxdb.VariableUpdate) (*influxdb.Variable, error) { var m influxdb.Variable err := s.Client. PatchJSON(update, prefixVariables, id.String()). @@ -531,7 +534,7 @@ func (s *VariableService) ReplaceVariable(ctx context.Context, variable *influxd } // DeleteVariable removes a variable from the store -func (s *VariableService) DeleteVariable(ctx context.Context, id influxdb.ID) error { +func (s *VariableService) DeleteVariable(ctx context.Context, id platform.ID) error { return s.Client. Delete(prefixVariables, id.String()). Do(ctx) diff --git a/http/variable_test.go b/http/variable_test.go index aeebc6634ec..fec278002a8 100644 --- a/http/variable_test.go +++ b/http/variable_test.go @@ -12,6 +12,9 @@ import ( "testing" "time" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" platform "github.com/influxdata/influxdb/v2" kithttp "github.com/influxdata/influxdb/v2/kit/transport/http" @@ -62,7 +65,7 @@ func TestVariableService_handleGetVariables(t *testing.T) { return []*platform.Variable{ { ID: itesting.MustIDBase16("6162207574726f71"), - OrganizationID: platform.ID(1), + OrganizationID: platform2.ID(1), Name: "variable-a", Selected: []string{"b"}, Arguments: &platform.VariableArguments{ @@ -76,7 +79,7 @@ func TestVariableService_handleGetVariables(t *testing.T) { }, { ID: itesting.MustIDBase16("61726920617a696f"), - OrganizationID: platform.ID(1), + OrganizationID: platform2.ID(1), Name: "variable-b", Selected: []string{"c"}, Arguments: &platform.VariableArguments{ @@ -363,10 +366,10 @@ func TestVariableService_handleGetVariable(t *testing.T) { }, fields: fields{ &mock.VariableService{ - FindVariableByIDF: func(ctx context.Context, id platform.ID) (*platform.Variable, error) { + FindVariableByIDF: func(ctx context.Context, id platform2.ID) (*platform.Variable, error) { return &platform.Variable{ ID: itesting.MustIDBase16("75650d0a636f6d70"), - OrganizationID: platform.ID(1), + OrganizationID: platform2.ID(1), Name: "variable-a", Selected: []string{"b"}, Arguments: &platform.VariableArguments{ @@ -394,9 +397,9 @@ func TestVariableService_handleGetVariable(t *testing.T) { }, fields: fields{ &mock.VariableService{ - FindVariableByIDF: func(ctx context.Context, id platform.ID) (*platform.Variable, error) { - return nil, &platform.Error{ - Code: platform.ENotFound, + FindVariableByIDF: func(ctx context.Context, id platform2.ID) (*platform.Variable, error) { + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: fmt.Sprintf("variable with ID %v not found", id), } }, @@ -415,7 +418,7 @@ func TestVariableService_handleGetVariable(t *testing.T) { }, fields: fields{ &mock.VariableService{ - FindVariableByIDF: func(ctx context.Context, id platform.ID) (*platform.Variable, error) { + FindVariableByIDF: func(ctx context.Context, id platform2.ID) (*platform.Variable, error) { return nil, nil }, }, @@ -493,7 +496,7 @@ func TestVariableService_handlePostVariable(t *testing.T) { &mock.VariableService{ CreateVariableF: func(ctx context.Context, m *platform.Variable) error { m.ID = itesting.MustIDBase16("75650d0a636f6d70") - m.OrganizationID = platform.ID(1) + m.OrganizationID = platform2.ID(1) m.UpdatedAt = faketime m.CreatedAt = faketime return nil @@ -624,7 +627,7 @@ func TestVariableService_handlePutVariable(t *testing.T) { &mock.VariableService{ ReplaceVariableF: func(ctx context.Context, m *platform.Variable) error { m.ID = itesting.MustIDBase16("75650d0a636f6d70") - m.OrganizationID = platform.ID(1) + m.OrganizationID = platform2.ID(1) m.UpdatedAt = faketime m.CreatedAt = faketime return nil @@ -725,10 +728,10 @@ func TestVariableService_handlePatchVariable(t *testing.T) { name: "update a variable name", fields: fields{ &mock.VariableService{ - UpdateVariableF: func(ctx context.Context, id platform.ID, u *platform.VariableUpdate) (*platform.Variable, error) { + UpdateVariableF: func(ctx context.Context, id platform2.ID, u *platform.VariableUpdate) (*platform.Variable, error) { return &platform.Variable{ ID: itesting.MustIDBase16("75650d0a636f6d70"), - OrganizationID: platform.ID(2), + OrganizationID: platform2.ID(2), Name: "new-name", Arguments: &platform.VariableArguments{ Type: "constant", @@ -831,7 +834,7 @@ func TestVariableService_handleDeleteVariable(t *testing.T) { name: "delete a variable", fields: fields{ &mock.VariableService{ - DeleteVariableF: func(ctx context.Context, id platform.ID) error { + DeleteVariableF: func(ctx context.Context, id platform2.ID) error { return nil }, }, @@ -847,9 +850,9 @@ func TestVariableService_handleDeleteVariable(t *testing.T) { name: "delete a non-existent variable", fields: fields{ &mock.VariableService{ - DeleteVariableF: func(ctx context.Context, id platform.ID) error { - return &platform.Error{ - Code: platform.ENotFound, + DeleteVariableF: func(ctx context.Context, id platform2.ID) error { + return &errors.Error{ + Code: errors.ENotFound, Msg: fmt.Sprintf("variable with ID %v not found", id), } }, @@ -899,7 +902,7 @@ func TestService_handlePostVariableLabel(t *testing.T) { } type args struct { labelMapping *platform.LabelMapping - variableID platform.ID + variableID platform2.ID } type wants struct { statusCode int @@ -917,7 +920,7 @@ func TestService_handlePostVariableLabel(t *testing.T) { name: "add label to variable", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctx context.Context, id platform.ID) (*platform.Label, error) { + FindLabelByIDFn: func(ctx context.Context, id platform2.ID) (*platform.Label, error) { return &platform.Label{ ID: 1, Name: "label", diff --git a/http/write_handler.go b/http/write_handler.go index 82ebd1ec945..3c3a38ce29c 100644 --- a/http/write_handler.go +++ b/http/write_handler.go @@ -7,6 +7,9 @@ import ( "io" "net/http" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/httprouter" "github.com/influxdata/influxdb/v2" pcontext "github.com/influxdata/influxdb/v2/context" @@ -23,7 +26,7 @@ import ( // WriteBackend is all services and associated parameters required to construct // the WriteHandler. type WriteBackend struct { - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler log *zap.Logger WriteEventRecorder metric.EventRecorder @@ -47,7 +50,7 @@ func NewWriteBackend(log *zap.Logger, b *APIBackend) *WriteBackend { // WriteHandler receives line protocol and sends to a publish function. type WriteHandler struct { - influxdb.HTTPErrorHandler + errors.HTTPErrorHandler BucketService influxdb.BucketService OrganizationService influxdb.OrganizationService PointsWriter storage.PointsWriter @@ -110,13 +113,13 @@ func NewWriteHandler(log *zap.Logger, b *WriteBackend, opts ...WriteHandlerOptio return h } -func (h *WriteHandler) findBucket(ctx context.Context, orgID influxdb.ID, bucket string) (*influxdb.Bucket, error) { - if id, err := influxdb.IDFromString(bucket); err == nil { +func (h *WriteHandler) findBucket(ctx context.Context, orgID platform.ID, bucket string) (*influxdb.Bucket, error) { + if id, err := platform.IDFromString(bucket); err == nil { b, err := h.BucketService.FindBucket(ctx, influxdb.BucketFilter{ OrganizationID: &orgID, ID: id, }) - if err != nil && influxdb.ErrorCode(err) != influxdb.ENotFound { + if err != nil && errors.ErrorCode(err) != errors.ENotFound { return nil, err } else if err == nil { return b, err @@ -189,8 +192,8 @@ func (h *WriteHandler) handleWrite(w http.ResponseWriter, r *http.Request) { if err := h.PointsWriter.WritePoints(ctx, org.ID, bucket.ID, parsed.Points); err != nil { if partialErr, ok := err.(tsdb.PartialWriteError); ok { - h.HandleHTTPError(ctx, &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + h.HandleHTTPError(ctx, &errors.Error{ + Code: errors.EUnprocessableEntity, Op: opWriteHandler, Msg: "failure writing points to database", Err: partialErr, @@ -198,8 +201,8 @@ func (h *WriteHandler) handleWrite(w http.ResponseWriter, r *http.Request) { return } - h.HandleHTTPError(ctx, &influxdb.Error{ - Code: influxdb.EInternal, + h.HandleHTTPError(ctx, &errors.Error{ + Code: errors.EInternal, Op: opWriteHandler, Msg: "unexpected error writing points to database", Err: err, @@ -212,19 +215,19 @@ func (h *WriteHandler) handleWrite(w http.ResponseWriter, r *http.Request) { // checkBucketWritePermissions checks an Authorizer for write permissions to a // specific Bucket. -func checkBucketWritePermissions(auth influxdb.Authorizer, orgID, bucketID influxdb.ID) error { +func checkBucketWritePermissions(auth influxdb.Authorizer, orgID, bucketID platform.ID) error { p, err := influxdb.NewPermissionAtID(bucketID, influxdb.WriteAction, influxdb.BucketsResourceType, orgID) if err != nil { - return &influxdb.Error{ - Code: influxdb.EInternal, + return &errors.Error{ + Code: errors.EInternal, Op: opWriteHandler, Msg: fmt.Sprintf("unable to create permission for bucket: %v", err), Err: err, } } if pset, err := auth.PermissionSet(); err != nil || !pset.Allowed(*p) { - return &influxdb.Error{ - Code: influxdb.EForbidden, + return &errors.Error{ + Code: errors.EForbidden, Op: opWriteHandler, Msg: "insufficient permissions for write", Err: err, @@ -252,8 +255,8 @@ func decodeWriteRequest(ctx context.Context, r *http.Request, maxBatchSizeBytes } if !models.ValidPrecision(precision) { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Op: "http/newWriteRequest", Msg: msgInvalidPrecision, } @@ -261,8 +264,8 @@ func decodeWriteRequest(ctx context.Context, r *http.Request, maxBatchSizeBytes bucket := qp.Get("bucket") if bucket == "" { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Op: "http/newWriteRequest", Msg: "bucket not found", } @@ -314,8 +317,8 @@ func (s *WriteService) WriteTo(ctx context.Context, filter influxdb.BucketFilter } if !models.ValidPrecision(precision) { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Op: "http/Write", Msg: msgInvalidPrecision, } diff --git a/http/write_handler_test.go b/http/write_handler_test.go index dec2c74ddb1..97e0ea3451b 100644 --- a/http/write_handler_test.go +++ b/http/write_handler_test.go @@ -11,6 +11,9 @@ import ( "strings" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/http/metric" httpmock "github.com/influxdata/influxdb/v2/http/mock" @@ -25,15 +28,15 @@ import ( func TestWriteService_WriteTo(t *testing.T) { type args struct { org string - orgId influxdb.ID + orgId platform.ID bucket string - bucketId influxdb.ID + bucketId platform.ID r io.Reader } - orgId := influxdb.ID(1) + orgId := platform.ID(1) org := "org" - bucketId := influxdb.ID(2) + bucketId := platform.ID(2) bucket := "bucket" tests := []struct { @@ -104,16 +107,16 @@ func TestWriteService_WriteTo(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var org, bucket *string - var orgId, bucketId *influxdb.ID + var orgId, bucketId *platform.ID var lp []byte ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { orgStr := r.URL.Query().Get("org") bucketStr := r.URL.Query().Get("bucket") var err error - if orgId, err = influxdb.IDFromString(orgStr); err != nil { + if orgId, err = platform.IDFromString(orgStr); err != nil { org = &orgStr } - if bucketId, err = influxdb.IDFromString(bucketStr); err != nil { + if bucketId, err = platform.IDFromString(bucketStr); err != nil { bucket = &bucketStr } defer r.Body.Close() @@ -248,7 +251,7 @@ func TestWriteHandler_handleWrite(t *testing.T) { auth: bucketWritePermission("043e0780ee2b1000", "04504b356e23b000"), }, state: state{ - orgErr: &influxdb.Error{Code: influxdb.ENotFound, Msg: "not found"}, + orgErr: &errors.Error{Code: errors.ENotFound, Msg: "not found"}, }, wants: wants{ code: 404, @@ -282,7 +285,7 @@ func TestWriteHandler_handleWrite(t *testing.T) { }, state: state{ org: testOrg("043e0780ee2b1000"), - bucketErr: &influxdb.Error{Code: influxdb.ENotFound, Msg: "not found"}, + bucketErr: &errors.Error{Code: errors.ENotFound, Msg: "not found"}, }, wants: wants{ code: 404, @@ -298,7 +301,7 @@ func TestWriteHandler_handleWrite(t *testing.T) { }, state: state{ org: testOrg("043e0780ee2b1000"), - bucketErr: &influxdb.Error{Code: influxdb.EInternal, Msg: "internal error"}, + bucketErr: &errors.Error{Code: errors.EInternal, Msg: "internal error"}, }, wants: wants{ code: 500, diff --git a/http/write_usage_recorder.go b/http/write_usage_recorder.go index 036f3b96bb0..2634710a606 100644 --- a/http/write_usage_recorder.go +++ b/http/write_usage_recorder.go @@ -3,7 +3,8 @@ package http import ( "context" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/http/metric" kithttp "github.com/influxdata/influxdb/v2/kit/transport/http" ) @@ -24,7 +25,7 @@ func (w *WriteUsageRecorder) Write(b []byte) (int, error) { return w.Writer.Write(b) } -func (w *WriteUsageRecorder) Record(ctx context.Context, requestBytes int, orgID influxdb.ID, endpoint string) { +func (w *WriteUsageRecorder) Record(ctx context.Context, requestBytes int, orgID platform.ID, endpoint string) { w.EventRecorder.Record(ctx, metric.Event{ OrgID: orgID, Endpoint: endpoint, diff --git a/influxql/_v1tests/server_helpers.go b/influxql/_v1tests/server_helpers.go index a2b8a5c3cf8..cd5d8cc1a09 100644 --- a/influxql/_v1tests/server_helpers.go +++ b/influxql/_v1tests/server_helpers.go @@ -3,6 +3,7 @@ package v1tests import ( "context" "encoding/json" + "github.com/influxdata/influxdb/v2/kit/platform" "io/ioutil" "net/http" "net/url" @@ -91,8 +92,8 @@ type Write struct { type Writes []*Write type Test struct { - orgID influxdb.ID - bucketID influxdb.ID + orgID platform.ID + bucketID platform.ID db string rp string writes Writes diff --git a/influxql/query/executor.go b/influxql/query/executor.go index 83e6d363691..0e7a2cb21b3 100644 --- a/influxql/query/executor.go +++ b/influxql/query/executor.go @@ -9,7 +9,8 @@ import ( "strconv" "time" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + iql "github.com/influxdata/influxdb/v2/influxql" "github.com/influxdata/influxdb/v2/influxql/control" "github.com/influxdata/influxdb/v2/kit/tracing" @@ -103,7 +104,7 @@ func AuthorizerIsOpen(a Authorizer) bool { // ExecutionOptions contains the options for executing a query. type ExecutionOptions struct { // OrgID is the organization for which this query is being executed. - OrgID influxdb.ID + OrgID platform.ID // The database the query is running against. Database string diff --git a/influxql/query/iterator.go b/influxql/query/iterator.go index b66e495447a..50cf1422c6b 100644 --- a/influxql/query/iterator.go +++ b/influxql/query/iterator.go @@ -9,8 +9,9 @@ import ( "regexp" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/gogo/protobuf/proto" - "github.com/influxdata/influxdb/v2" internal "github.com/influxdata/influxdb/v2/influxql/query/internal" "github.com/influxdata/influxql" ) @@ -541,7 +542,7 @@ type IteratorCreator interface { // IteratorOptions is an object passed to CreateIterator to specify creation options. type IteratorOptions struct { // OrgID is the organization for which this query is being executed. - OrgID influxdb.ID + OrgID platform.ID // Expression to iterate for. // This can be VarRef or a Call. diff --git a/influxql/query/proxy_executor.go b/influxql/query/proxy_executor.go index 25c20db0ed7..241cc489cfd 100644 --- a/influxql/query/proxy_executor.go +++ b/influxql/query/proxy_executor.go @@ -6,7 +6,8 @@ import ( "strings" "time" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + iql "github.com/influxdata/influxdb/v2/influxql" "github.com/influxdata/influxdb/v2/kit/check" "github.com/influxdata/influxdb/v2/kit/tracing" @@ -40,8 +41,8 @@ func (s *ProxyExecutor) Query(ctx context.Context, w io.Writer, req *iql.QueryRe p.SetParams(req.Params) q, err := p.ParseQuery() if err != nil { - return iql.Statistics{}, &influxdb.Error{ - Code: influxdb.EInvalid, + return iql.Statistics{}, &errors.Error{ + Code: errors.EInvalid, Msg: "failed to parse query", Err: err, } diff --git a/influxql/query/select.go b/influxql/query/select.go index ad52b3ca025..58ea0f37fb2 100644 --- a/influxql/query/select.go +++ b/influxql/query/select.go @@ -8,7 +8,8 @@ import ( "sync" "time" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + iql "github.com/influxdata/influxdb/v2/influxql" "github.com/influxdata/influxdb/v2/influxql/query/internal/gota" "github.com/influxdata/influxql" @@ -23,7 +24,7 @@ var DefaultTypeMapper = influxql.MultiTypeMapper( // SelectOptions are options that customize the select call. type SelectOptions struct { // OrgID is the organization for which this query is being executed. - OrgID influxdb.ID + OrgID platform.ID // Node to exclusively read from. // If zero, all nodes are used. diff --git a/influxql/query_request.go b/influxql/query_request.go index 564220daeb8..7b7b3e380e4 100644 --- a/influxql/query_request.go +++ b/influxql/query_request.go @@ -3,6 +3,9 @@ package influxql import ( "encoding/json" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) @@ -60,7 +63,7 @@ func (f EncodingFormat) ContentType() string { type QueryRequest struct { Authorization *influxdb.Authorization `json:"authorization,omitempty"` - OrganizationID influxdb.ID `json:"organization_id"` + OrganizationID platform.ID `json:"organization_id"` DB string `json:"db"` RP string `json:"rp"` Epoch string `json:"epoch"` @@ -76,9 +79,9 @@ type QueryRequest struct { // The HTTP query requests represented the body expected by the QueryHandler func (r *QueryRequest) Valid() error { if !r.OrganizationID.Valid() { - return &influxdb.Error{ + return &errors.Error{ Msg: "organization_id is not valid", - Code: influxdb.EInvalid, + Code: errors.EInvalid, } } return r.Authorization.Valid() diff --git a/inmem/dbrp_mapping_service.go b/inmem/dbrp_mapping_service.go index f21a1c21435..c951e646332 100644 --- a/inmem/dbrp_mapping_service.go +++ b/inmem/dbrp_mapping_service.go @@ -5,12 +5,14 @@ import ( "fmt" "path" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) var ( - errDBRPMappingNotFound = &influxdb.Error{ - Code: influxdb.ENotFound, + errDBRPMappingNotFound = &errors.Error{ + Code: errors.ENotFound, Msg: "dbrp mapping not found", } ) @@ -71,8 +73,8 @@ func (s *Service) filterDBRPMappings(ctx context.Context, fn func(m *influxdb.DB // Find returns the first dbrp mapping that matches filter. func (s *Service) Find(ctx context.Context, filter influxdb.DBRPMappingFilter) (*influxdb.DBRPMapping, error) { if filter.Cluster == nil && filter.Database == nil && filter.RetentionPolicy == nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "no filter parameters provided", } } @@ -135,8 +137,8 @@ func (s *Service) Create(ctx context.Context, m *influxdb.DBRPMapping) error { } if !existing.Equal(m) { - return &influxdb.Error{ - Code: influxdb.EConflict, + return &errors.Error{ + Code: errors.EConflict, Msg: "dbrp mapping already exists", } } diff --git a/inmem/service.go b/inmem/service.go index c025c4b105f..7344c4d8547 100644 --- a/inmem/service.go +++ b/inmem/service.go @@ -4,6 +4,8 @@ import ( "context" "sync" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/rand" "github.com/influxdata/influxdb/v2/snowflake" @@ -33,7 +35,7 @@ type Service struct { sourceKV sync.Map TokenGenerator platform.TokenGenerator - IDGenerator platform.IDGenerator + IDGenerator platform2.IDGenerator platform.TimeGenerator } diff --git a/inmem/source.go b/inmem/source.go index 13f1281b72e..57018937894 100644 --- a/inmem/source.go +++ b/inmem/source.go @@ -4,6 +4,9 @@ import ( "context" "fmt" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + platform "github.com/influxdata/influxdb/v2" ) @@ -33,11 +36,11 @@ func init() { func (s *Service) initializeSources(ctx context.Context) error { _, pe := s.FindSourceByID(ctx, DefaultSource.ID) - if pe != nil && platform.ErrorCode(pe) != platform.ENotFound { + if pe != nil && errors.ErrorCode(pe) != errors.ENotFound { return pe } - if platform.ErrorCode(pe) == platform.ENotFound { + if errors.ErrorCode(pe) == errors.ENotFound { if err := s.PutSource(ctx, &DefaultSource); err != nil { return err } @@ -59,27 +62,27 @@ func (s *Service) DefaultSource(ctx context.Context) (*platform.Source, error) { return src, nil } } - return nil, &platform.Error{ - Code: platform.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: "no default source found", } } // FindSourceByID retrieves a source by id. -func (s *Service) FindSourceByID(ctx context.Context, id platform.ID) (*platform.Source, error) { +func (s *Service) FindSourceByID(ctx context.Context, id platform2.ID) (*platform.Source, error) { i, ok := s.sourceKV.Load(id.String()) if !ok { - return nil, &platform.Error{ - Code: platform.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: platform.ErrSourceNotFound, } } src, ok := i.(*platform.Source) if !ok { - return nil, &platform.Error{ - Code: platform.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("type %T is not a source", i), } } diff --git a/internal/resource/resolve.go b/internal/resource/resolve.go index c2e3730643b..baff55a56be 100644 --- a/internal/resource/resolve.go +++ b/internal/resource/resolve.go @@ -4,6 +4,9 @@ import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) @@ -14,45 +17,45 @@ import ( // Consider it deprecated. type Resolver struct { AuthorizationFinder interface { - FindAuthorizationByID(context.Context, influxdb.ID) (*influxdb.Authorization, error) + FindAuthorizationByID(context.Context, platform.ID) (*influxdb.Authorization, error) } BucketFinder interface { - FindBucketByID(context.Context, influxdb.ID) (*influxdb.Bucket, error) + FindBucketByID(context.Context, platform.ID) (*influxdb.Bucket, error) } OrganizationFinder interface { - FindOrganizationByID(context.Context, influxdb.ID) (*influxdb.Organization, error) + FindOrganizationByID(context.Context, platform.ID) (*influxdb.Organization, error) } DashboardFinder interface { - FindDashboardByID(context.Context, influxdb.ID) (*influxdb.Dashboard, error) + FindDashboardByID(context.Context, platform.ID) (*influxdb.Dashboard, error) } SourceFinder interface { - FindSourceByID(context.Context, influxdb.ID) (*influxdb.Source, error) + FindSourceByID(context.Context, platform.ID) (*influxdb.Source, error) } TaskFinder interface { - FindTaskByID(context.Context, influxdb.ID) (*influxdb.Task, error) + FindTaskByID(context.Context, platform.ID) (*influxdb.Task, error) } TelegrafConfigFinder interface { - FindTelegrafConfigByID(context.Context, influxdb.ID) (*influxdb.TelegrafConfig, error) + FindTelegrafConfigByID(context.Context, platform.ID) (*influxdb.TelegrafConfig, error) } VariableFinder interface { - FindVariableByID(context.Context, influxdb.ID) (*influxdb.Variable, error) + FindVariableByID(context.Context, platform.ID) (*influxdb.Variable, error) } TargetFinder interface { - GetTargetByID(context.Context, influxdb.ID) (*influxdb.ScraperTarget, error) + GetTargetByID(context.Context, platform.ID) (*influxdb.ScraperTarget, error) } CheckFinder interface { - FindCheckByID(context.Context, influxdb.ID) (influxdb.Check, error) + FindCheckByID(context.Context, platform.ID) (influxdb.Check, error) } NotificationEndpointFinder interface { - FindNotificationEndpointByID(context.Context, influxdb.ID) (influxdb.NotificationEndpoint, error) + FindNotificationEndpointByID(context.Context, platform.ID) (influxdb.NotificationEndpoint, error) } NotificationRuleFinder interface { - FindNotificationRuleByID(context.Context, influxdb.ID) (influxdb.NotificationRule, error) + FindNotificationRuleByID(context.Context, platform.ID) (influxdb.NotificationRule, error) } } // FindResourceOrganizationID is used to find the organization that a resource belongs to five the id of a resource and a resource type. -func (o *Resolver) FindResourceOrganizationID(ctx context.Context, rt influxdb.ResourceType, id influxdb.ID) (influxdb.ID, error) { +func (o *Resolver) FindResourceOrganizationID(ctx context.Context, rt influxdb.ResourceType, id platform.ID) (platform.ID, error) { switch rt { case influxdb.AuthorizationsResourceType: if o.AuthorizationFinder == nil { @@ -61,7 +64,7 @@ func (o *Resolver) FindResourceOrganizationID(ctx context.Context, rt influxdb.R r, err := o.AuthorizationFinder.FindAuthorizationByID(ctx, id) if err != nil { - return influxdb.InvalidID(), err + return platform.InvalidID(), err } return r.OrgID, nil @@ -72,7 +75,7 @@ func (o *Resolver) FindResourceOrganizationID(ctx context.Context, rt influxdb.R r, err := o.BucketFinder.FindBucketByID(ctx, id) if err != nil { - return influxdb.InvalidID(), err + return platform.InvalidID(), err } return r.OrgID, nil @@ -83,7 +86,7 @@ func (o *Resolver) FindResourceOrganizationID(ctx context.Context, rt influxdb.R r, err := o.OrganizationFinder.FindOrganizationByID(ctx, id) if err != nil { - return influxdb.InvalidID(), err + return platform.InvalidID(), err } return r.ID, nil @@ -94,7 +97,7 @@ func (o *Resolver) FindResourceOrganizationID(ctx context.Context, rt influxdb.R r, err := o.DashboardFinder.FindDashboardByID(ctx, id) if err != nil { - return influxdb.InvalidID(), err + return platform.InvalidID(), err } return r.OrganizationID, nil @@ -105,7 +108,7 @@ func (o *Resolver) FindResourceOrganizationID(ctx context.Context, rt influxdb.R r, err := o.SourceFinder.FindSourceByID(ctx, id) if err != nil { - return influxdb.InvalidID(), err + return platform.InvalidID(), err } return r.OrganizationID, nil @@ -116,7 +119,7 @@ func (o *Resolver) FindResourceOrganizationID(ctx context.Context, rt influxdb.R r, err := o.TaskFinder.FindTaskByID(ctx, id) if err != nil { - return influxdb.InvalidID(), err + return platform.InvalidID(), err } return r.OrganizationID, nil @@ -127,7 +130,7 @@ func (o *Resolver) FindResourceOrganizationID(ctx context.Context, rt influxdb.R r, err := o.TelegrafConfigFinder.FindTelegrafConfigByID(ctx, id) if err != nil { - return influxdb.InvalidID(), err + return platform.InvalidID(), err } return r.OrgID, nil @@ -138,7 +141,7 @@ func (o *Resolver) FindResourceOrganizationID(ctx context.Context, rt influxdb.R r, err := o.VariableFinder.FindVariableByID(ctx, id) if err != nil { - return influxdb.InvalidID(), err + return platform.InvalidID(), err } return r.OrganizationID, nil @@ -149,7 +152,7 @@ func (o *Resolver) FindResourceOrganizationID(ctx context.Context, rt influxdb.R r, err := o.TargetFinder.GetTargetByID(ctx, id) if err != nil { - return influxdb.InvalidID(), err + return platform.InvalidID(), err } return r.OrgID, nil @@ -160,7 +163,7 @@ func (o *Resolver) FindResourceOrganizationID(ctx context.Context, rt influxdb.R r, err := o.CheckFinder.FindCheckByID(ctx, id) if err != nil { - return influxdb.InvalidID(), err + return platform.InvalidID(), err } return r.GetOrgID(), nil @@ -171,7 +174,7 @@ func (o *Resolver) FindResourceOrganizationID(ctx context.Context, rt influxdb.R r, err := o.NotificationEndpointFinder.FindNotificationEndpointByID(ctx, id) if err != nil { - return influxdb.InvalidID(), err + return platform.InvalidID(), err } return r.GetOrgID(), nil @@ -182,19 +185,19 @@ func (o *Resolver) FindResourceOrganizationID(ctx context.Context, rt influxdb.R r, err := o.NotificationRuleFinder.FindNotificationRuleByID(ctx, id) if err != nil { - return influxdb.InvalidID(), err + return platform.InvalidID(), err } return r.GetOrgID(), nil } - return influxdb.InvalidID(), &influxdb.Error{ + return platform.InvalidID(), &errors.Error{ Msg: fmt.Sprintf("unsupported resource type %s", rt), } } // FindResourceName is used to find the name of the resource associated with the provided type and id. -func (o *Resolver) FindResourceName(ctx context.Context, rt influxdb.ResourceType, id influxdb.ID) (string, error) { +func (o *Resolver) FindResourceName(ctx context.Context, rt influxdb.ResourceType, id platform.ID) (string, error) { switch rt { case influxdb.AuthorizationsResourceType: // keeping this consistent with the original kv implementation diff --git a/jsonweb/token.go b/jsonweb/token.go index da29723d96b..21ed0a6e14c 100644 --- a/jsonweb/token.go +++ b/jsonweb/token.go @@ -3,6 +3,8 @@ package jsonweb import ( "errors" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/dgrijalva/jwt-go" "github.com/influxdata/influxdb/v2" ) @@ -100,10 +102,10 @@ func (t *Token) PermissionSet() (influxdb.PermissionSet, error) { // Identifier returns the identifier for this Token // as found in the standard claims -func (t *Token) Identifier() influxdb.ID { - id, err := influxdb.IDFromString(t.Id) +func (t *Token) Identifier() platform.ID { + id, err := platform.IDFromString(t.Id) if err != nil || id == nil { - return influxdb.ID(1) + return platform.ID(1) } return *id @@ -111,10 +113,10 @@ func (t *Token) Identifier() influxdb.ID { // GetUserID returns an invalid id as tokens are generated // with permissions rather than for or by a particular user -func (t *Token) GetUserID() influxdb.ID { - id, err := influxdb.IDFromString(t.UserID) +func (t *Token) GetUserID() platform.ID { + id, err := platform.IDFromString(t.UserID) if err != nil { - return influxdb.InvalidID() + return platform.InvalidID() } return *id } @@ -125,7 +127,7 @@ func (t *Token) Kind() string { } // EphemeralAuth creates a influxdb Auth form a jwt token -func (t *Token) EphemeralAuth(orgID influxdb.ID) *influxdb.Authorization { +func (t *Token) EphemeralAuth(orgID platform.ID) *influxdb.Authorization { return &influxdb.Authorization{ ID: t.Identifier(), OrgID: orgID, diff --git a/jsonweb/token_test.go b/jsonweb/token_test.go index cda65f8c62e..e69f56223cb 100644 --- a/jsonweb/token_test.go +++ b/jsonweb/token_test.go @@ -4,14 +4,16 @@ import ( "reflect" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/dgrijalva/jwt-go" "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" ) var ( - one = influxdb.ID(1) - two = influxdb.ID(2) + one = platform.ID(1) + two = platform.ID(2) keyStore = KeyStoreFunc(func(kid string) ([]byte, error) { if kid != "some-key" { return nil, ErrKeyNotFound diff --git a/kit/cli/idflag.go b/kit/cli/idflag.go index 81c02c0943b..a6a5be5521f 100644 --- a/kit/cli/idflag.go +++ b/kit/cli/idflag.go @@ -1,22 +1,22 @@ package cli import ( - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" "github.com/spf13/cobra" "github.com/spf13/pflag" ) // Wrapper for influxdb.ID -type idValue influxdb.ID +type idValue platform.ID -func newIDValue(val influxdb.ID, p *influxdb.ID) *idValue { +func newIDValue(val platform.ID, p *platform.ID) *idValue { *p = val return (*idValue)(p) } -func (i *idValue) String() string { return influxdb.ID(*i).String() } +func (i *idValue) String() string { return platform.ID(*i).String() } func (i *idValue) Set(s string) error { - id, err := influxdb.IDFromString(s) + id, err := platform.IDFromString(s) if err != nil { return err } @@ -30,31 +30,31 @@ func (i *idValue) Type() string { // IDVar defines an influxdb.ID flag with specified name, default value, and usage string. // The argument p points to an influxdb.ID variable in which to store the value of the flag. -func IDVar(fs *pflag.FlagSet, p *influxdb.ID, name string, value influxdb.ID, usage string) { +func IDVar(fs *pflag.FlagSet, p *platform.ID, name string, value platform.ID, usage string) { IDVarP(fs, p, name, "", value, usage) } // IDVarP is like IDVar, but accepts a shorthand letter that can be used after a single dash. -func IDVarP(fs *pflag.FlagSet, p *influxdb.ID, name, shorthand string, value influxdb.ID, usage string) { +func IDVarP(fs *pflag.FlagSet, p *platform.ID, name, shorthand string, value platform.ID, usage string) { fs.VarP(newIDValue(value, p), name, shorthand, usage) } type OrgBucket struct { - Org influxdb.ID - Bucket influxdb.ID + Org platform.ID + Bucket platform.ID } func (o *OrgBucket) AddFlags(cmd *cobra.Command) { fs := cmd.Flags() - IDVar(fs, &o.Org, "org-id", influxdb.InvalidID(), "organization id") - IDVar(fs, &o.Bucket, "bucket-id", influxdb.InvalidID(), "bucket id") + IDVar(fs, &o.Org, "org-id", platform.InvalidID(), "organization id") + IDVar(fs, &o.Bucket, "bucket-id", platform.InvalidID(), "bucket id") } -func (o *OrgBucket) OrgBucketID() (orgID, bucketID influxdb.ID) { +func (o *OrgBucket) OrgBucketID() (orgID, bucketID platform.ID) { return o.Org, o.Bucket } -func (o *OrgBucket) Name() [influxdb.IDLength]byte { +func (o *OrgBucket) Name() [platform.IDLength]byte { // TODO: FIX THIS panic("TODO: Fix") } diff --git a/kit/cli/viper.go b/kit/cli/viper.go index ce1691e626d..7cbbb5f5295 100644 --- a/kit/cli/viper.go +++ b/kit/cli/viper.go @@ -7,7 +7,8 @@ import ( "strings" "time" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/spf13/cast" "github.com/spf13/cobra" "github.com/spf13/pflag" @@ -307,10 +308,10 @@ func BindOptions(v *viper.Viper, cmd *cobra.Command, opts []Opt) error { } } - case *influxdb.ID: - var d influxdb.ID + case *platform.ID: + var d platform.ID if o.Default != nil { - d = o.Default.(influxdb.ID) + d = o.Default.(platform.ID) } if hasShort { IDVarP(flagset, destP, o.Flag, string(o.Short), d, o.Desc) diff --git a/kit/metric/client.go b/kit/metric/client.go index b234c982ed0..299a86ec1bb 100644 --- a/kit/metric/client.go +++ b/kit/metric/client.go @@ -3,7 +3,8 @@ package metric import ( "time" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/prometheus/client_golang/prometheus" ) @@ -32,7 +33,7 @@ func New(reg prometheus.Registerer, service string, opts ...ClientOptFn) *REDCli if o.Err != nil { vec.With(prometheus.Labels{ "method": o.Method, - "code": influxdb.ErrorCode(o.Err), + "code": errors.ErrorCode(o.Err), }).Inc() } }, diff --git a/error.go b/kit/platform/errors/error.go similarity index 93% rename from error.go rename to kit/platform/errors/error.go index 42c34a1d14a..fb2f5eec7ae 100644 --- a/error.go +++ b/kit/platform/errors/error.go @@ -1,4 +1,4 @@ -package influxdb +package errors // ChronografError is a domain error encountered while processing chronograf requests. type ChronografError string diff --git a/errors.go b/kit/platform/errors/errors.go similarity index 99% rename from errors.go rename to kit/platform/errors/errors.go index 22000c7a5b4..8a3a1a3d98c 100644 --- a/errors.go +++ b/kit/platform/errors/errors.go @@ -1,4 +1,4 @@ -package influxdb +package errors import ( "context" diff --git a/errors.md b/kit/platform/errors/errors.md similarity index 100% rename from errors.md rename to kit/platform/errors/errors.md diff --git a/errors_test.go b/kit/platform/errors/errors_test.go similarity index 72% rename from errors_test.go rename to kit/platform/errors/errors_test.go index d30e3015e20..597b156081d 100644 --- a/errors_test.go +++ b/kit/platform/errors/errors_test.go @@ -1,12 +1,11 @@ -package influxdb_test +package errors_test import ( "encoding/json" "errors" "fmt" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" "testing" - - platform "github.com/influxdata/influxdb/v2" ) const EFailedToGetStorageHost = "failed to get the storage host" @@ -19,20 +18,20 @@ func TestErrorMsg(t *testing.T) { }{ { name: "simple error", - err: &platform.Error{Code: platform.ENotFound}, + err: &errors2.Error{Code: errors2.ENotFound}, msg: "", }, { name: "with message", - err: &platform.Error{ - Code: platform.ENotFound, + err: &errors2.Error{ + Code: errors2.ENotFound, Msg: "bucket not found", }, msg: "bucket not found", }, { name: "with a third party error and no message", - err: &platform.Error{ + err: &errors2.Error{ Code: EFailedToGetStorageHost, Err: errors.New("empty value"), }, @@ -40,7 +39,7 @@ func TestErrorMsg(t *testing.T) { }, { name: "with a third party error and a message", - err: &platform.Error{ + err: &errors2.Error{ Code: EFailedToGetStorageHost, Msg: "failed to get storage hosts", Err: errors.New("empty value"), @@ -49,10 +48,10 @@ func TestErrorMsg(t *testing.T) { }, { name: "with an internal error and no message", - err: &platform.Error{ + err: &errors2.Error{ Code: EFailedToGetStorageHost, - Err: &platform.Error{ - Code: platform.EEmptyValue, + Err: &errors2.Error{ + Code: errors2.EEmptyValue, Msg: "empty value", }, }, @@ -60,11 +59,11 @@ func TestErrorMsg(t *testing.T) { }, { name: "with an internal error and a message", - err: &platform.Error{ + err: &errors2.Error{ Code: EFailedToGetStorageHost, Msg: "failed to get storage hosts", - Err: &platform.Error{ - Code: platform.EEmptyValue, + Err: &errors2.Error{ + Code: errors2.EEmptyValue, Msg: "empty value", }, }, @@ -89,16 +88,16 @@ func TestErrorMessage(t *testing.T) { }, { name: "nil error of type *platform.Error", - err: (*platform.Error)(nil), + err: (*errors2.Error)(nil), }, { name: "simple error", - err: &platform.Error{Msg: "simple error"}, + err: &errors2.Error{Msg: "simple error"}, want: "simple error", }, { name: "embedded error", - err: &platform.Error{Err: &platform.Error{Msg: "embedded error"}}, + err: &errors2.Error{Err: &errors2.Error{Msg: "embedded error"}}, want: "embedded error", }, { @@ -108,7 +107,7 @@ func TestErrorMessage(t *testing.T) { }, } for _, c := range cases { - if result := platform.ErrorMessage(c.err); c.want != result { + if result := errors2.ErrorMessage(c.err); c.want != result { t.Errorf("%s failed, want %s, got %s", c.name, c.want, result) } } @@ -125,21 +124,21 @@ func TestErrorOp(t *testing.T) { }, { name: "nil error of type *platform.Error", - err: (*platform.Error)(nil), + err: (*errors2.Error)(nil), }, { name: "simple error", - err: &platform.Error{Op: "op1"}, + err: &errors2.Error{Op: "op1"}, want: "op1", }, { name: "embedded error", - err: &platform.Error{Op: "op1", Err: &platform.Error{Code: platform.EInvalid}}, + err: &errors2.Error{Op: "op1", Err: &errors2.Error{Code: errors2.EInvalid}}, want: "op1", }, { name: "embedded error without op in root level", - err: &platform.Error{Err: &platform.Error{Code: platform.EInvalid, Op: "op2"}}, + err: &errors2.Error{Err: &errors2.Error{Code: errors2.EInvalid, Op: "op2"}}, want: "op2", }, { @@ -149,7 +148,7 @@ func TestErrorOp(t *testing.T) { }, } for _, c := range cases { - if result := platform.ErrorOp(c.err); c.want != result { + if result := errors2.ErrorOp(c.err); c.want != result { t.Errorf("%s failed, want %s, got %s", c.name, c.want, result) } } @@ -165,31 +164,31 @@ func TestErrorCode(t *testing.T) { }, { name: "nil error of type *platform.Error", - err: (*platform.Error)(nil), + err: (*errors2.Error)(nil), }, { name: "simple error", - err: &platform.Error{Code: platform.ENotFound}, - want: platform.ENotFound, + err: &errors2.Error{Code: errors2.ENotFound}, + want: errors2.ENotFound, }, { name: "embedded error", - err: &platform.Error{Code: platform.ENotFound, Err: &platform.Error{Code: platform.EInvalid}}, - want: platform.ENotFound, + err: &errors2.Error{Code: errors2.ENotFound, Err: &errors2.Error{Code: errors2.EInvalid}}, + want: errors2.ENotFound, }, { name: "embedded error with root level code", - err: &platform.Error{Err: &platform.Error{Code: platform.EInvalid}}, - want: platform.EInvalid, + err: &errors2.Error{Err: &errors2.Error{Code: errors2.EInvalid}}, + want: errors2.EInvalid, }, { name: "default error", err: errors.New("s"), - want: platform.EInternal, + want: errors2.EInternal, }, } for _, c := range cases { - if result := platform.ErrorCode(c.err); c.want != result { + if result := errors2.ErrorCode(c.err); c.want != result { t.Errorf("%s failed, want %s, got %s", c.name, c.want, result) } } @@ -198,26 +197,26 @@ func TestErrorCode(t *testing.T) { func TestJSON(t *testing.T) { cases := []struct { name string - err *platform.Error + err *errors2.Error encoded string }{ { name: "simple error", - err: &platform.Error{Code: platform.ENotFound}, + err: &errors2.Error{Code: errors2.ENotFound}, encoded: `{"code":"not found"}`, }, { name: "with op", - err: &platform.Error{ - Code: platform.ENotFound, + err: &errors2.Error{ + Code: errors2.ENotFound, Op: "bolt.FindAuthorizationByID", }, encoded: `{"code":"not found","op":"bolt.FindAuthorizationByID"}`, }, { name: "with op and value", - err: &platform.Error{ - Code: platform.ENotFound, + err: &errors2.Error{ + Code: errors2.ENotFound, Op: "bolt/FindAuthorizationByID", Msg: fmt.Sprintf("with ID %d", 323), }, @@ -225,7 +224,7 @@ func TestJSON(t *testing.T) { }, { name: "with a third party error", - err: &platform.Error{ + err: &errors2.Error{ Code: EFailedToGetStorageHost, Op: "cmd/fluxd.injectDeps", Err: errors.New("empty value"), @@ -234,23 +233,23 @@ func TestJSON(t *testing.T) { }, { name: "with a internal error", - err: &platform.Error{ + err: &errors2.Error{ Code: EFailedToGetStorageHost, Op: "cmd/fluxd.injectDeps", - Err: &platform.Error{Code: platform.EEmptyValue, Op: "cmd/fluxd.getStrList"}, + Err: &errors2.Error{Code: errors2.EEmptyValue, Op: "cmd/fluxd.getStrList"}, }, encoded: `{"code":"failed to get the storage host","op":"cmd/fluxd.injectDeps","error":{"code":"empty value","op":"cmd/fluxd.getStrList"}}`, }, { name: "with a deep internal error", - err: &platform.Error{ + err: &errors2.Error{ Code: EFailedToGetStorageHost, Op: "cmd/fluxd.injectDeps", - Err: &platform.Error{ - Code: platform.EInvalid, + Err: &errors2.Error{ + Code: errors2.EInvalid, Op: "cmd/fluxd.getStrList", - Err: &platform.Error{ - Code: platform.EEmptyValue, + Err: &errors2.Error{ + Code: errors2.EEmptyValue, Err: errors.New("an err"), }, }, @@ -269,7 +268,7 @@ func TestJSON(t *testing.T) { t.Errorf("%s encode failed, want result: %s, got %s", c.name, c.encoded, string(result)) } // decode testing - got := new(platform.Error) + got := new(errors2.Error) err = json.Unmarshal(result, got) if err != nil { t.Errorf("%s decode failed, want err: %v, should be nil", c.name, err) @@ -278,7 +277,7 @@ func TestJSON(t *testing.T) { } } -func decodeEqual(t *testing.T, want, result *platform.Error, caseName string) { +func decodeEqual(t *testing.T, want, result *errors2.Error, caseName string) { if want.Code != result.Code { t.Errorf("%s code failed, want %s, got %s", caseName, want.Code, result.Code) } @@ -289,8 +288,8 @@ func decodeEqual(t *testing.T, want, result *platform.Error, caseName string) { t.Errorf("%s msg failed, want %s, got %s", caseName, want.Msg, result.Msg) } if want.Err != nil { - if _, ok := want.Err.(*platform.Error); ok { - decodeEqual(t, want.Err.(*platform.Error), result.Err.(*platform.Error), caseName) + if _, ok := want.Err.(*errors2.Error); ok { + decodeEqual(t, want.Err.(*errors2.Error), result.Err.(*errors2.Error), caseName) } else { if want.Err.Error() != result.Err.Error() { t.Errorf("%s Err failed, want %s, got %s", caseName, want.Err.Error(), result.Err.Error()) diff --git a/id.go b/kit/platform/id.go similarity index 92% rename from id.go rename to kit/platform/id.go index 125c177f568..af6a8a49777 100644 --- a/id.go +++ b/kit/platform/id.go @@ -1,10 +1,12 @@ -package influxdb +package platform import ( "encoding/binary" "encoding/hex" "strconv" "unsafe" + + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) // IDLength is the exact length a string (or a byte slice representing it) must have in order to be decoded into a valid ID. @@ -12,22 +14,22 @@ const IDLength = 16 var ( // ErrInvalidID signifies invalid IDs. - ErrInvalidID = &Error{ - Code: EInvalid, + ErrInvalidID = &errors.Error{ + Code: errors.EInvalid, Msg: "invalid ID", } // ErrInvalidIDLength is returned when an ID has the incorrect number of bytes. - ErrInvalidIDLength = &Error{ - Code: EInvalid, + ErrInvalidIDLength = &errors.Error{ + Code: errors.EInvalid, Msg: "id must have a length of 16 bytes", } ) // ErrCorruptID means the ID stored in the Store is corrupt. -func ErrCorruptID(err error) *Error { - return &Error{ - Code: EInvalid, +func ErrCorruptID(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInvalid, Msg: "corrupt ID provided", Err: err, } diff --git a/id_test.go b/kit/platform/id_test.go similarity index 86% rename from id_test.go rename to kit/platform/id_test.go index 5c7746857e9..00090bd894b 100644 --- a/id_test.go +++ b/kit/platform/id_test.go @@ -1,13 +1,13 @@ -package influxdb_test +package platform_test import ( "bytes" "encoding/json" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" "reflect" "testing" - "github.com/influxdata/influxdb/v2" platformtesting "github.com/influxdata/influxdb/v2/testing" ) @@ -15,7 +15,7 @@ func TestIDFromString(t *testing.T) { tests := []struct { name string id string - want influxdb.ID + want platform.ID wantErr bool err string }{ @@ -23,7 +23,7 @@ func TestIDFromString(t *testing.T) { name: "Should be able to decode an all zeros ID", id: "0000000000000000", wantErr: true, - err: influxdb.ErrInvalidID.Error(), + err: platform.ErrInvalidID.Error(), }, { name: "Should be able to decode an all f ID", @@ -39,24 +39,24 @@ func TestIDFromString(t *testing.T) { name: "Should not be able to decode a non hex ID", id: "gggggggggggggggg", wantErr: true, - err: influxdb.ErrInvalidID.Error(), + err: platform.ErrInvalidID.Error(), }, { name: "Should not be able to decode inputs with length less than 16 bytes", id: "abc", wantErr: true, - err: influxdb.ErrInvalidIDLength.Error(), + err: platform.ErrInvalidIDLength.Error(), }, { name: "Should not be able to decode inputs with length greater than 16 bytes", id: "abcdabcdabcdabcd0", wantErr: true, - err: influxdb.ErrInvalidIDLength.Error(), + err: platform.ErrInvalidIDLength.Error(), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := influxdb.IDFromString(tt.id) + got, err := platform.IDFromString(tt.id) // Check negative test cases if (err != nil) && tt.wantErr { @@ -75,7 +75,7 @@ func TestIDFromString(t *testing.T) { } func TestDecodeFromString(t *testing.T) { - var id influxdb.ID + var id platform.ID err := id.DecodeFromString("020f755c3c082000") if err != nil { t.Errorf(err.Error()) @@ -94,7 +94,7 @@ func TestDecodeFromString(t *testing.T) { } func TestEncode(t *testing.T) { - var id influxdb.ID + var id platform.ID if _, err := id.Encode(); err == nil { t.Errorf("encoding an invalid ID should not be possible") } @@ -114,15 +114,15 @@ func TestEncode(t *testing.T) { } func TestDecodeFromAllZeros(t *testing.T) { - var id influxdb.ID - err := id.Decode(make([]byte, influxdb.IDLength)) + var id platform.ID + err := id.Decode(make([]byte, platform.IDLength)) if err == nil { t.Errorf("expecting all zeros ID to not be a valid ID") } } func TestDecodeFromShorterString(t *testing.T) { - var id influxdb.ID + var id platform.ID err := id.DecodeFromString("020f75") if err == nil { t.Errorf("expecting shorter inputs to error") @@ -133,7 +133,7 @@ func TestDecodeFromShorterString(t *testing.T) { } func TestDecodeFromLongerString(t *testing.T) { - var id influxdb.ID + var id platform.ID err := id.DecodeFromString("020f755c3c082000aaa") if err == nil { t.Errorf("expecting shorter inputs to error") @@ -144,7 +144,7 @@ func TestDecodeFromLongerString(t *testing.T) { } func TestDecodeFromEmptyString(t *testing.T) { - var id influxdb.ID + var id platform.ID err := id.DecodeFromString("") if err == nil { t.Errorf("expecting empty inputs to error") @@ -155,14 +155,14 @@ func TestDecodeFromEmptyString(t *testing.T) { } func TestMarshalling(t *testing.T) { - var id0 influxdb.ID + var id0 platform.ID _, err := json.Marshal(id0) if err == nil { t.Errorf("expecting empty ID to not be a valid one") } init := "ca55e77eca55e77e" - id1, err := influxdb.IDFromString(init) + id1, err := platform.IDFromString(init) if err != nil { t.Errorf(err.Error()) } @@ -172,7 +172,7 @@ func TestMarshalling(t *testing.T) { t.Errorf(err.Error()) } - var id2 influxdb.ID + var id2 platform.ID json.Unmarshal(serialized, &id2) bytes1, _ := id1.Encode() @@ -184,7 +184,7 @@ func TestMarshalling(t *testing.T) { // When used as a map key, IDs must use their string encoding. // If you only implement json.Marshaller, they will be encoded with Go's default integer encoding. - b, err := json.Marshal(map[influxdb.ID]int{0x1234: 5678}) + b, err := json.Marshal(map[platform.ID]int{0x1234: 5678}) if err != nil { t.Error(err) } @@ -193,7 +193,7 @@ func TestMarshalling(t *testing.T) { t.Errorf("expected map to json.Marshal as %s; got %s", exp, string(b)) } - var idMap map[influxdb.ID]int + var idMap map[platform.ID]int if err := json.Unmarshal(b, &idMap); err != nil { t.Error(err) } @@ -206,19 +206,19 @@ func TestMarshalling(t *testing.T) { } func TestValid(t *testing.T) { - var id influxdb.ID + var id platform.ID if id.Valid() { t.Errorf("expecting initial ID to be invalid") } - if influxdb.InvalidID() != 0 { + if platform.InvalidID() != 0 { t.Errorf("expecting invalid ID to return a zero ID, thus invalid") } } func TestID_GoString(t *testing.T) { type idGoStringTester struct { - ID influxdb.ID + ID platform.ID } var x idGoStringTester @@ -228,14 +228,14 @@ func TestID_GoString(t *testing.T) { } sharpV := fmt.Sprintf("%#v", x) - want := `influxdb_test.idGoStringTester{ID:"` + idString + `"}` + want := `platform_test.idGoStringTester{ID:"` + idString + `"}` if sharpV != want { t.Fatalf("bad GoString: got %q, want %q", sharpV, want) } } func BenchmarkIDEncode(b *testing.B) { - var id influxdb.ID + var id platform.ID id.DecodeFromString("5ca1ab1eba5eba11") b.ResetTimer() for i := 0; i < b.N; i++ { @@ -246,7 +246,7 @@ func BenchmarkIDEncode(b *testing.B) { func BenchmarkIDDecode(b *testing.B) { for i := 0; i < b.N; i++ { - var id influxdb.ID + var id platform.ID id.DecodeFromString("5ca1ab1eba5eba11") } } diff --git a/kit/transport/http/api.go b/kit/transport/http/api.go index 3e4f4133930..69a2983ae28 100644 --- a/kit/transport/http/api.go +++ b/kit/transport/http/api.go @@ -9,7 +9,8 @@ import ( "io" "net/http" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "go.uber.org/zap" ) @@ -82,8 +83,8 @@ func NewAPI(opts ...APIOptFn) *API { logger: zap.NewNop(), prettyJSON: true, unmarshalErrFn: func(encoding string, err error) error { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("failed to unmarshal %s: %s", encoding, err), } }, @@ -92,7 +93,7 @@ func NewAPI(opts ...APIOptFn) *API { if msg == "" { msg = "an internal error has occurred" } - code := influxdb.ErrorCode(err) + code := errors.ErrorCode(err) return ErrBody{ Code: code, Msg: msg, diff --git a/kit/transport/http/api_test.go b/kit/transport/http/api_test.go index 54bdb65dca0..ae233afa335 100644 --- a/kit/transport/http/api_test.go +++ b/kit/transport/http/api_test.go @@ -5,12 +5,12 @@ import ( "encoding/gob" "encoding/json" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "io" "net/http" "strings" "testing" - "github.com/influxdata/influxdb/v2" kithttp "github.com/influxdata/influxdb/v2/kit/transport/http" "github.com/influxdata/influxdb/v2/pkg/testttp" "github.com/stretchr/testify/assert" @@ -93,7 +93,7 @@ func Test_API(t *testing.T) { var out validatFoo err := api.DecodeJSON(bytes.NewReader(invalidBody), &out) - expectInfluxdbError(t, influxdb.EInvalid, err) + expectInfluxdbError(t, errors.EInvalid, err) }) t.Run("gob", func(t *testing.T) { @@ -103,7 +103,7 @@ func Test_API(t *testing.T) { var out validatFoo err := api.DecodeGob(bytes.NewReader(invalidBody), &out) - expectInfluxdbError(t, influxdb.EInvalid, err) + expectInfluxdbError(t, errors.EInvalid, err) }) }) @@ -115,7 +115,7 @@ func Test_API(t *testing.T) { var out validatFoo err := api.DecodeJSON(encodeJSON(t, badFoo), &out) - expectInfluxdbError(t, influxdb.EUnprocessableEntity, err) + expectInfluxdbError(t, errors.EUnprocessableEntity, err) }) t.Run("gob", func(t *testing.T) { @@ -123,7 +123,7 @@ func Test_API(t *testing.T) { var out validatFoo err := api.DecodeGob(encodeGob(t, badFoo), &out) - expectInfluxdbError(t, influxdb.EUnprocessableEntity, err) + expectInfluxdbError(t, errors.EUnprocessableEntity, err) }) }) }) @@ -171,33 +171,33 @@ func Test_API(t *testing.T) { t.Run("Err", func(t *testing.T) { tests := []struct { statusCode int - expectedErr *influxdb.Error + expectedErr *errors.Error }{ { statusCode: http.StatusBadRequest, - expectedErr: &influxdb.Error{ - Code: influxdb.EInvalid, + expectedErr: &errors.Error{ + Code: errors.EInvalid, Msg: "failed to unmarshal", }, }, { statusCode: http.StatusForbidden, - expectedErr: &influxdb.Error{ - Code: influxdb.EForbidden, + expectedErr: &errors.Error{ + Code: errors.EForbidden, Msg: "forbidden", }, }, { statusCode: http.StatusUnprocessableEntity, - expectedErr: &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + expectedErr: &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: "failed validation", }, }, { statusCode: http.StatusInternalServerError, - expectedErr: &influxdb.Error{ - Code: influxdb.EInternal, + expectedErr: &errors.Error{ + Code: errors.EInternal, Msg: "internal error", }, }, @@ -233,7 +233,7 @@ func expectInfluxdbError(t *testing.T, expectedCode string, err error) { if err == nil { t.Fatal("expected an error") } - iErr, ok := err.(*influxdb.Error) + iErr, ok := err.(*errors.Error) if !ok { t.Fatalf("expected an influxdb error; got=%#v", err) } @@ -264,16 +264,16 @@ func encodeJSON(t *testing.T, v interface{}) io.Reader { } func okErrFn(err error) error { - return &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + return &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: "failed validation", Err: err, } } func unmarshalErrFn(encoding string, err error) error { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("invalid %s request body", encoding), Err: err, } diff --git a/kit/transport/http/error_handler.go b/kit/transport/http/error_handler.go index cdb13693947..166c94d3202 100644 --- a/kit/transport/http/error_handler.go +++ b/kit/transport/http/error_handler.go @@ -11,7 +11,7 @@ import ( "net/http" "strings" - "github.com/influxdata/influxdb/v2" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" ) // ErrorHandler is the error handler in http package. @@ -26,9 +26,9 @@ func (h ErrorHandler) HandleHTTPError(ctx context.Context, err error, w http.Res return } - code := influxdb.ErrorCode(err) + code := errors2.ErrorCode(err) var msg string - if err, ok := err.(*influxdb.Error); ok { + if err, ok := err.(*errors2.Error); ok { msg = err.Error() } else { msg = "An internal error has occurred" @@ -60,7 +60,7 @@ func StatusCodeToErrorCode(statusCode int) string { return errorCode } - return influxdb.EInternal + return errors2.EInternal } // ErrorCodeToStatusCode maps an influxdb error code string to a @@ -85,19 +85,19 @@ func ErrorCodeToStatusCode(ctx context.Context, code string) int { // influxDBErrorToStatusCode is a mapping of ErrorCode to http status code. var influxDBErrorToStatusCode = map[string]int{ - influxdb.EInternal: http.StatusInternalServerError, - influxdb.ENotImplemented: http.StatusNotImplemented, - influxdb.EInvalid: http.StatusBadRequest, - influxdb.EUnprocessableEntity: http.StatusUnprocessableEntity, - influxdb.EEmptyValue: http.StatusBadRequest, - influxdb.EConflict: http.StatusUnprocessableEntity, - influxdb.ENotFound: http.StatusNotFound, - influxdb.EUnavailable: http.StatusServiceUnavailable, - influxdb.EForbidden: http.StatusForbidden, - influxdb.ETooManyRequests: http.StatusTooManyRequests, - influxdb.EUnauthorized: http.StatusUnauthorized, - influxdb.EMethodNotAllowed: http.StatusMethodNotAllowed, - influxdb.ETooLarge: http.StatusRequestEntityTooLarge, + errors2.EInternal: http.StatusInternalServerError, + errors2.ENotImplemented: http.StatusNotImplemented, + errors2.EInvalid: http.StatusBadRequest, + errors2.EUnprocessableEntity: http.StatusUnprocessableEntity, + errors2.EEmptyValue: http.StatusBadRequest, + errors2.EConflict: http.StatusUnprocessableEntity, + errors2.ENotFound: http.StatusNotFound, + errors2.EUnavailable: http.StatusServiceUnavailable, + errors2.EForbidden: http.StatusForbidden, + errors2.ETooManyRequests: http.StatusTooManyRequests, + errors2.EUnauthorized: http.StatusUnauthorized, + errors2.EMethodNotAllowed: http.StatusMethodNotAllowed, + errors2.ETooLarge: http.StatusRequestEntityTooLarge, } var httpStatusCodeToInfluxDBError = map[int]string{} @@ -136,13 +136,13 @@ func CheckError(resp *http.Response) (err error) { return nil default: // TODO(jsternberg): Figure out what to do here? - return &influxdb.Error{ - Code: influxdb.EInternal, + return &errors2.Error{ + Code: errors2.EInternal, Msg: fmt.Sprintf("unexpected status code: %d %s", resp.StatusCode, resp.Status), } } - perr := &influxdb.Error{ + perr := &errors2.Error{ Code: StatusCodeToErrorCode(resp.StatusCode), } diff --git a/kit/transport/http/error_handler_test.go b/kit/transport/http/error_handler_test.go index 2c152620ce9..0ebd19553d5 100644 --- a/kit/transport/http/error_handler_test.go +++ b/kit/transport/http/error_handler_test.go @@ -3,10 +3,10 @@ package http_test import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "net/http/httptest" "testing" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/http" kithttp "github.com/influxdata/influxdb/v2/kit/transport/http" ) @@ -25,8 +25,8 @@ func TestEncodeError(t *testing.T) { func TestEncodeErrorWithError(t *testing.T) { ctx := context.TODO() - err := &influxdb.Error{ - Code: influxdb.EInternal, + err := &errors.Error{ + Code: errors.EInternal, Msg: "an error occurred", Err: fmt.Errorf("there's an error here, be aware"), } @@ -40,15 +40,15 @@ func TestEncodeErrorWithError(t *testing.T) { } errHeader := w.Header().Get("X-Platform-Error-Code") - if errHeader != influxdb.EInternal { - t.Errorf("expected X-Platform-Error-Code: %s, got: %s", influxdb.EInternal, errHeader) + if errHeader != errors.EInternal { + t.Errorf("expected X-Platform-Error-Code: %s, got: %s", errors.EInternal, errHeader) } // The http handler will flatten the message and it will not // have an error property, so reading the serialization results // in a different error. - pe := http.CheckError(w.Result()).(*influxdb.Error) - if want, got := influxdb.EInternal, pe.Code; want != got { + pe := http.CheckError(w.Result()).(*errors.Error) + if want, got := errors.EInternal, pe.Code; want != got { t.Errorf("unexpected code -want/+got:\n\t- %q\n\t+ %q", want, got) } if want, got := "an error occurred: there's an error here, be aware", pe.Msg; want != got { diff --git a/kit/transport/http/middleware.go b/kit/transport/http/middleware.go index 4ca1032c05f..1643736a505 100644 --- a/kit/transport/http/middleware.go +++ b/kit/transport/http/middleware.go @@ -8,8 +8,10 @@ import ( "strings" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/tracing" ua "github.com/mileusna/useragent" "github.com/prometheus/client_golang/prometheus" @@ -113,8 +115,8 @@ func normalizePath(p string) string { var parts []string for head, tail := shiftPath(p); ; head, tail = shiftPath(tail) { piece := head - if len(piece) == influxdb.IDLength { - if _, err := influxdb.IDFromString(head); err == nil { + if len(piece) == platform.IDLength { + if _, err := platform.IDFromString(head); err == nil { piece = ":id" } } @@ -140,13 +142,13 @@ type OrgContext string const CtxOrgKey OrgContext = "orgID" // ValidResource make sure a resource exists when a sub system needs to be mounted to an api -func ValidResource(api *API, lookupOrgByResourceID func(context.Context, influxdb.ID) (influxdb.ID, error)) Middleware { +func ValidResource(api *API, lookupOrgByResourceID func(context.Context, platform.ID) (platform.ID, error)) Middleware { return func(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { statusW := NewStatusResponseWriter(w) - id, err := influxdb.IDFromString(chi.URLParam(r, "id")) + id, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { - api.Err(w, r, influxdb.ErrCorruptID(err)) + api.Err(w, r, platform.ErrCorruptID(err)) return } @@ -155,8 +157,8 @@ func ValidResource(api *API, lookupOrgByResourceID func(context.Context, influxd orgID, err := lookupOrgByResourceID(ctx, *id) if err != nil { // if this function returns an error we will squash the error message and replace it with a not found error - api.Err(w, r, &influxdb.Error{ - Code: influxdb.ENotFound, + api.Err(w, r, &errors.Error{ + Code: errors.ENotFound, Msg: "404 page not found", }) return @@ -170,11 +172,11 @@ func ValidResource(api *API, lookupOrgByResourceID func(context.Context, influxd } // OrgIDFromContext .... -func OrgIDFromContext(ctx context.Context) *influxdb.ID { +func OrgIDFromContext(ctx context.Context) *platform.ID { v := ctx.Value(CtxOrgKey) if v == nil { return nil } - id := v.(influxdb.ID) + id := v.(platform.ID) return &id } diff --git a/kit/transport/http/middleware_test.go b/kit/transport/http/middleware_test.go index 875a9920f1e..5a500498692 100644 --- a/kit/transport/http/middleware_test.go +++ b/kit/transport/http/middleware_test.go @@ -5,7 +5,8 @@ import ( "path" "testing" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/pkg/testttp" "github.com/stretchr/testify/assert" ) @@ -18,7 +19,7 @@ func Test_normalizePath(t *testing.T) { }{ { name: "1", - path: path.Join("/api/v2/organizations", influxdb.ID(2).String()), + path: path.Join("/api/v2/organizations", platform.ID(2).String()), expected: "/api/v2/organizations/:id", }, { @@ -33,7 +34,7 @@ func Test_normalizePath(t *testing.T) { }, { name: "4", - path: path.Join("/api/v2/organizations", influxdb.ID(2).String(), "users", influxdb.ID(3).String()), + path: path.Join("/api/v2/organizations", platform.ID(2).String(), "users", platform.ID(3).String()), expected: "/api/v2/organizations/:id/users/:id", }, } diff --git a/kv/document.go b/kv/document.go index cda35992ede..9c16adcbde9 100644 --- a/kv/document.go +++ b/kv/document.go @@ -5,6 +5,9 @@ import ( "encoding/json" "path" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) @@ -93,7 +96,7 @@ func (s *Service) putDocument(ctx context.Context, tx Tx, ns string, d *influxdb return nil } -func (s *Service) putAtID(ctx context.Context, tx Tx, bucket string, id influxdb.ID, i interface{}) error { +func (s *Service) putAtID(ctx context.Context, tx Tx, bucket string, id platform.ID, i interface{}) error { v, err := json.Marshal(i) if err != nil { return err @@ -116,11 +119,11 @@ func (s *Service) putAtID(ctx context.Context, tx Tx, bucket string, id influxdb return nil } -func (s *Service) putDocumentContent(ctx context.Context, tx Tx, ns string, id influxdb.ID, data interface{}) error { +func (s *Service) putDocumentContent(ctx context.Context, tx Tx, ns string, id platform.ID, data interface{}) error { return s.putAtID(ctx, tx, path.Join(ns, documentContentBucket), id, data) } -func (s *Service) putDocumentMeta(ctx context.Context, tx Tx, ns string, id influxdb.ID, m influxdb.DocumentMeta) error { +func (s *Service) putDocumentMeta(ctx context.Context, tx Tx, ns string, id platform.ID, m influxdb.DocumentMeta) error { return s.putAtID(ctx, tx, path.Join(ns, documentMetaBucket), id, m) } @@ -130,7 +133,7 @@ func (s *DocumentStore) PutDocument(ctx context.Context, d *influxdb.Document) e }) } -func (s *Service) findByID(ctx context.Context, tx Tx, bucket string, id influxdb.ID, i interface{}) error { +func (s *Service) findByID(ctx context.Context, tx Tx, bucket string, id platform.ID, i interface{}) error { b, err := tx.Bucket([]byte(bucket)) if err != nil { return err @@ -153,7 +156,7 @@ func (s *Service) findByID(ctx context.Context, tx Tx, bucket string, id influxd return nil } -func (s *Service) findDocumentMetaByID(ctx context.Context, tx Tx, ns string, id influxdb.ID) (*influxdb.DocumentMeta, error) { +func (s *Service) findDocumentMetaByID(ctx context.Context, tx Tx, ns string, id platform.ID) (*influxdb.DocumentMeta, error) { m := &influxdb.DocumentMeta{} if err := s.findByID(ctx, tx, path.Join(ns, documentMetaBucket), id, m); err != nil { @@ -163,7 +166,7 @@ func (s *Service) findDocumentMetaByID(ctx context.Context, tx Tx, ns string, id return m, nil } -func (s *Service) findDocumentContentByID(ctx context.Context, tx Tx, ns string, id influxdb.ID) (interface{}, error) { +func (s *Service) findDocumentContentByID(ctx context.Context, tx Tx, ns string, id platform.ID) (interface{}, error) { var data interface{} if err := s.findByID(ctx, tx, path.Join(ns, documentContentBucket), id, &data); err != nil { return nil, err @@ -173,7 +176,7 @@ func (s *Service) findDocumentContentByID(ctx context.Context, tx Tx, ns string, } // FindDocument retrieves the specified document with all its content and labels. -func (s *DocumentStore) FindDocument(ctx context.Context, id influxdb.ID) (*influxdb.Document, error) { +func (s *DocumentStore) FindDocument(ctx context.Context, id platform.ID) (*influxdb.Document, error) { var d *influxdb.Document err := s.service.kv.View(ctx, func(tx Tx) error { m, err := s.service.findDocumentMetaByID(ctx, tx, s.namespace, id) @@ -194,8 +197,8 @@ func (s *DocumentStore) FindDocument(ctx context.Context, id influxdb.ID) (*infl }) if IsNotFound(err) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrDocumentNotFound, } } @@ -208,7 +211,7 @@ func (s *DocumentStore) FindDocument(ctx context.Context, id influxdb.ID) (*infl } // FindDocuments retrieves all documents returned by the document find options. -func (s *DocumentStore) FindDocuments(ctx context.Context, _ influxdb.ID) ([]*influxdb.Document, error) { +func (s *DocumentStore) FindDocuments(ctx context.Context, _ platform.ID) ([]*influxdb.Document, error) { var ds []*influxdb.Document err := s.service.kv.View(ctx, func(tx Tx) error { diff --git a/kv/encode.go b/kv/encode.go index 62c5071e2be..bcbdcf008dc 100644 --- a/kv/encode.go +++ b/kv/encode.go @@ -4,7 +4,7 @@ import ( "errors" "strings" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" ) // EncodeFn returns an encoding when called. Closures are your friend here. @@ -39,7 +39,7 @@ func EncStringCaseInsensitive(str string) EncodeFn { } // EncID encodes an influx ID. -func EncID(id influxdb.ID) EncodeFn { +func EncID(id platform.ID) EncodeFn { return func() ([]byte, error) { if id == 0 { return nil, errors.New("no ID was provided") diff --git a/kv/errors.go b/kv/errors.go index 8a38935d261..43742b42150 100644 --- a/kv/errors.go +++ b/kv/errors.go @@ -3,13 +3,13 @@ package kv import ( "fmt" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) // UnexpectedIndexError is used when the error comes from an internal system. -func UnexpectedIndexError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func UnexpectedIndexError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("unexpected error retrieving index; Err: %v", err), Op: "kv/index", } @@ -17,7 +17,7 @@ func UnexpectedIndexError(err error) *influxdb.Error { // NotUniqueError is used when attempting to create a resource that already // exists. -var NotUniqueError = &influxdb.Error{ - Code: influxdb.EConflict, +var NotUniqueError = &errors.Error{ + Code: errors.EConflict, Msg: "name already exists", } diff --git a/kv/initial_migration.go b/kv/initial_migration.go index 9b7d45c53bf..441ad94cf74 100644 --- a/kv/initial_migration.go +++ b/kv/initial_migration.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" - influxdb "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" ) type InitialMigration struct{} @@ -80,7 +80,7 @@ func (m InitialMigration) Down(ctx context.Context, store SchemaStore) error { return nil } -func putAsJson(tx Tx, bucket []byte, id influxdb.ID, value interface{}) error { +func putAsJson(tx Tx, bucket []byte, id platform.ID, value interface{}) error { data, err := json.Marshal(value) if err != nil { return err diff --git a/kv/kvlog.go b/kv/kvlog.go index 672024150b9..92be19470aa 100644 --- a/kv/kvlog.go +++ b/kv/kvlog.go @@ -9,6 +9,8 @@ import ( "fmt" "time" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + platform "github.com/influxdata/influxdb/v2" ) @@ -18,8 +20,8 @@ var ( // ErrKeyValueLogBoundsNotFound is returned when oplog entries cannot be located // for the provided bounds - ErrKeyValueLogBoundsNotFound = &platform.Error{ - Code: platform.ENotFound, + ErrKeyValueLogBoundsNotFound = &errors.Error{ + Code: errors.ENotFound, Msg: "oplog not found", } ) diff --git a/kv/migration/all/0003_task_owners.go b/kv/migration/all/0003_task_owners.go index bd3c074ae85..0aa9f5f44fc 100644 --- a/kv/migration/all/0003_task_owners.go +++ b/kv/migration/all/0003_task_owners.go @@ -5,6 +5,9 @@ import ( "encoding/json" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" ) @@ -69,7 +72,7 @@ var Migration0003_TaskOwnerIDUpMigration = UpOnlyMigration( return influxdb.ErrTaskNotFound } authType := struct { - AuthorizationID influxdb.ID `json:"authorizationID"` + AuthorizationID platform.ID `json:"authorizationID"` }{} if err := json.Unmarshal(v, &authType); err != nil { return influxdb.ErrInternalTaskServiceError(err) @@ -131,8 +134,8 @@ var Migration0003_TaskOwnerIDUpMigration = UpOnlyMigration( // if population fails return error if !t.OwnerID.Valid() { - return &influxdb.Error{ - Code: influxdb.EInternal, + return &errors.Error{ + Code: errors.EInternal, Msg: "could not populate owner ID for task", } } @@ -158,11 +161,11 @@ var Migration0003_TaskOwnerIDUpMigration = UpOnlyMigration( ) type kvTask struct { - ID influxdb.ID `json:"id"` + ID platform.ID `json:"id"` Type string `json:"type,omitempty"` - OrganizationID influxdb.ID `json:"orgID"` + OrganizationID platform.ID `json:"orgID"` Organization string `json:"org"` - OwnerID influxdb.ID `json:"ownerID"` + OwnerID platform.ID `json:"ownerID"` Name string `json:"name"` Description string `json:"description,omitempty"` Status string `json:"status"` @@ -203,7 +206,7 @@ func kvToInfluxTask(k *kvTask) *influxdb.Task { } } -func taskKey(taskID influxdb.ID) ([]byte, error) { +func taskKey(taskID platform.ID) ([]byte, error) { encodedID, err := taskID.Encode() if err != nil { return nil, influxdb.ErrInvalidTaskID diff --git a/kv/migration/all/0003_task_owners_test.go b/kv/migration/all/0003_task_owners_test.go index 111eb7e310f..2c195ae577e 100644 --- a/kv/migration/all/0003_task_owners_test.go +++ b/kv/migration/all/0003_task_owners_test.go @@ -5,7 +5,8 @@ import ( "fmt" "testing" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kv" ) @@ -40,7 +41,7 @@ func Test_(t *testing.T) { t.Fatal(err) } - idType, _ := influxdb.IDFromString(id) + idType, _ := platform.IDFromString(id) task, err := ts.Service.FindTaskByID(context.Background(), *idType) if err != nil { t.Fatal(err) diff --git a/kv/migration/all/0011_populate-dashboards-owner-id.go b/kv/migration/all/0011_populate-dashboards-owner-id.go index a2ba3607e80..e2977fe538a 100644 --- a/kv/migration/all/0011_populate-dashboards-owner-id.go +++ b/kv/migration/all/0011_populate-dashboards-owner-id.go @@ -5,6 +5,8 @@ import ( "encoding/json" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" ) @@ -13,11 +15,11 @@ import ( var Migration0011_PopulateDashboardsOwnerId = UpOnlyMigration("populate dashboards owner id", func(ctx context.Context, store kv.SchemaStore) error { var urmBucket = []byte("userresourcemappingsv1") type userResourceMapping struct { - UserID influxdb.ID `json:"userID"` + UserID platform.ID `json:"userID"` UserType influxdb.UserType `json:"userType"` MappingType influxdb.MappingType `json:"mappingType"` ResourceType influxdb.ResourceType `json:"resourceType"` - ResourceID influxdb.ID `json:"resourceID"` + ResourceID platform.ID `json:"resourceID"` } var mappings []*userResourceMapping @@ -54,13 +56,13 @@ var Migration0011_PopulateDashboardsOwnerId = UpOnlyMigration("populate dashboar var dashboardsBucket = []byte("dashboardsv2") // dashboard represents all visual and query data for a dashboard. type dashboard struct { - ID influxdb.ID `json:"id,omitempty"` - OrganizationID influxdb.ID `json:"orgID,omitempty"` + ID platform.ID `json:"id,omitempty"` + OrganizationID platform.ID `json:"orgID,omitempty"` Name string `json:"name"` Description string `json:"description"` Cells []*influxdb.Cell `json:"cells"` Meta influxdb.DashboardMeta `json:"meta"` - OwnerID *influxdb.ID `json:"owner,omitempty"` + OwnerID *platform.ID `json:"owner,omitempty"` } var ( diff --git a/kv/migration/all/0013_repair-DBRP-owner-and-bucket-IDs.go b/kv/migration/all/0013_repair-DBRP-owner-and-bucket-IDs.go index c5863bc25d8..cdc4fb9657d 100644 --- a/kv/migration/all/0013_repair-DBRP-owner-and-bucket-IDs.go +++ b/kv/migration/all/0013_repair-DBRP-owner-and-bucket-IDs.go @@ -4,7 +4,8 @@ import ( "context" "encoding/json" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kv" ) @@ -12,14 +13,14 @@ var Migration0013_RepairDBRPOwnerAndBucketIDs = UpOnlyMigration( "repair DBRP owner and bucket IDs", func(ctx context.Context, store kv.SchemaStore) error { type oldStyleMapping struct { - ID influxdb.ID `json:"id"` + ID platform.ID `json:"id"` Database string `json:"database"` RetentionPolicy string `json:"retention_policy"` Default bool `json:"default"` // These 2 fields were renamed. - OrganizationID influxdb.ID `json:"organization_id"` - BucketID influxdb.ID `json:"bucket_id"` + OrganizationID platform.ID `json:"organization_id"` + BucketID platform.ID `json:"bucket_id"` } // Collect DBRPs that are using the old schema. @@ -55,14 +56,14 @@ var Migration0013_RepairDBRPOwnerAndBucketIDs = UpOnlyMigration( } type newStyleDbrpMapping struct { - ID influxdb.ID `json:"id"` + ID platform.ID `json:"id"` Database string `json:"database"` RetentionPolicy string `json:"retention_policy"` Default bool `json:"default"` // New names for the 2 renamed fields. - OrganizationID influxdb.ID `json:"orgID"` - BucketID influxdb.ID `json:"bucketID"` + OrganizationID platform.ID `json:"orgID"` + BucketID platform.ID `json:"bucketID"` } batchSize := 100 writeBatch := func(batch []*oldStyleMapping) (err error) { diff --git a/kv/migration/all/0015_record-shard-group-durations-in-bucket-metadata.go b/kv/migration/all/0015_record-shard-group-durations-in-bucket-metadata.go index 79581270063..f2542a54bb4 100644 --- a/kv/migration/all/0015_record-shard-group-durations-in-bucket-metadata.go +++ b/kv/migration/all/0015_record-shard-group-durations-in-bucket-metadata.go @@ -5,7 +5,8 @@ import ( "encoding/json" "time" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kv" "github.com/influxdata/influxdb/v2/v1/services/meta" ) @@ -14,8 +15,8 @@ var Migration0015_RecordShardGroupDurationsInBucketMetadata = UpOnlyMigration( "record shard group durations in bucket metadata", func(ctx context.Context, store kv.SchemaStore) error { type bucket struct { - ID influxdb.ID `json:"id,omitempty"` - OrgID influxdb.ID `json:"orgID,omitempty"` + ID platform.ID `json:"id,omitempty"` + OrgID platform.ID `json:"orgID,omitempty"` Type int `json:"type"` Name string `json:"name"` Description string `json:"description"` diff --git a/kv/migration/all/0015_record-shard-group-durations-in-bucket-metadata_test.go b/kv/migration/all/0015_record-shard-group-durations-in-bucket-metadata_test.go index f95a0206d2e..a7bd7804d1a 100644 --- a/kv/migration/all/0015_record-shard-group-durations-in-bucket-metadata_test.go +++ b/kv/migration/all/0015_record-shard-group-durations-in-bucket-metadata_test.go @@ -6,6 +6,8 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/dustin/go-humanize" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" @@ -22,25 +24,25 @@ func TestMigration_ShardGroupDuration(t *testing.T) { // Seed some buckets. buckets := []*influxdb.Bucket{ { - ID: influxdb.ID(1), + ID: platform.ID(1), Name: "infinite", OrgID: ts.Org.ID, RetentionPeriod: 0, }, { - ID: influxdb.ID(2), + ID: platform.ID(2), Name: "1w", OrgID: ts.Org.ID, RetentionPeriod: humanize.Week, }, { - ID: influxdb.ID(3), + ID: platform.ID(3), Name: "1d", OrgID: ts.Org.ID, RetentionPeriod: humanize.Day, }, { - ID: influxdb.ID(4), + ID: platform.ID(4), Name: "1h", OrgID: ts.Org.ID, RetentionPeriod: time.Hour, diff --git a/kv/migration/migration.go b/kv/migration/migration.go index bccce5319c3..6ba3090dab2 100644 --- a/kv/migration/migration.go +++ b/kv/migration/migration.go @@ -7,7 +7,8 @@ import ( "fmt" "time" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kv" "go.uber.org/zap" ) @@ -46,7 +47,7 @@ func (s MigrationState) String() string { // Migration is a record of a particular migration. type Migration struct { - ID influxdb.ID `json:"id"` + ID platform.ID `json:"id"` Name string `json:"name"` State MigrationState `json:"-"` StartedAt *time.Time `json:"started_at"` @@ -101,7 +102,7 @@ func (m *Migrator) AddMigrations(ms ...Spec) { // List returns a list of migrations and their states within the provided store. func (m *Migrator) List(ctx context.Context) (migrations []Migration, _ error) { - if err := m.walk(ctx, m.store, func(id influxdb.ID, m Migration) { + if err := m.walk(ctx, m.store, func(id platform.ID, m Migration) { migrations = append(migrations, m) }); err != nil { return nil, err @@ -110,7 +111,7 @@ func (m *Migrator) List(ctx context.Context) (migrations []Migration, _ error) { migrationsLen := len(migrations) for idx, spec := range m.Specs[migrationsLen:] { migration := Migration{ - ID: influxdb.ID(migrationsLen + idx + 1), + ID: platform.ID(migrationsLen + idx + 1), Name: spec.MigrationName(), } @@ -139,7 +140,7 @@ func (m *Migrator) Up(ctx context.Context) error { } var lastMigration int - if err := m.walk(ctx, m.store, func(id influxdb.ID, mig Migration) { + if err := m.walk(ctx, m.store, func(id platform.ID, mig Migration) { // we're interested in the last up migration if mig.State == UpMigrationState { lastMigration = int(id) @@ -156,7 +157,7 @@ func (m *Migrator) Up(ctx context.Context) error { for idx, spec := range m.Specs[lastMigration:] { startedAt := m.now() migration := Migration{ - ID: influxdb.ID(lastMigration + idx + 1), + ID: platform.ID(lastMigration + idx + 1), Name: spec.MigrationName(), StartedAt: &startedAt, } @@ -208,7 +209,7 @@ func (m *Migrator) Down(ctx context.Context) (err error) { Migration } - if err := m.walk(ctx, m.store, func(id influxdb.ID, mig Migration) { + if err := m.walk(ctx, m.store, func(id platform.ID, mig Migration) { migrations = append( migrations, struct { @@ -256,7 +257,7 @@ func (m *Migrator) logMigrationEvent(state MigrationState, mig Migration, event ) } -func (m *Migrator) walk(ctx context.Context, store kv.Store, fn func(id influxdb.ID, m Migration)) error { +func (m *Migrator) walk(ctx context.Context, store kv.Store, fn func(id platform.ID, m Migration)) error { if err := store.View(ctx, func(tx kv.Tx) error { bkt, err := tx.Bucket(migrationBucket) if err != nil { @@ -269,7 +270,7 @@ func (m *Migrator) walk(ctx context.Context, store kv.Store, fn func(id influxdb } return kv.WalkCursor(ctx, cursor, func(k, v []byte) (bool, error) { - var id influxdb.ID + var id platform.ID if err := id.Decode(k); err != nil { return false, fmt.Errorf("decoding migration id: %w", err) } diff --git a/kv/scrapers.go b/kv/scrapers.go index d70a94c4d8a..b405c06a310 100644 --- a/kv/scrapers.go +++ b/kv/scrapers.go @@ -5,42 +5,45 @@ import ( "encoding/json" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) var ( // ErrScraperNotFound is used when the scraper configuration is not found. - ErrScraperNotFound = &influxdb.Error{ + ErrScraperNotFound = &errors.Error{ Msg: "scraper target is not found", - Code: influxdb.ENotFound, + Code: errors.ENotFound, } // ErrInvalidScraperID is used when the service was provided // an invalid ID format. - ErrInvalidScraperID = &influxdb.Error{ - Code: influxdb.EInvalid, + ErrInvalidScraperID = &errors.Error{ + Code: errors.EInvalid, Msg: "provided scraper target ID has invalid format", } // ErrInvalidScrapersBucketID is used when the service was provided // an invalid ID format. - ErrInvalidScrapersBucketID = &influxdb.Error{ - Code: influxdb.EInvalid, + ErrInvalidScrapersBucketID = &errors.Error{ + Code: errors.EInvalid, Msg: "provided bucket ID has invalid format", } // ErrInvalidScrapersOrgID is used when the service was provided // an invalid ID format. - ErrInvalidScrapersOrgID = &influxdb.Error{ - Code: influxdb.EInvalid, + ErrInvalidScrapersOrgID = &errors.Error{ + Code: errors.EInvalid, Msg: "provided organization ID has invalid format", } ) // UnexpectedScrapersBucketError is used when the error comes from an internal system. -func UnexpectedScrapersBucketError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func UnexpectedScrapersBucketError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: "unexpected error retrieving scrapers bucket", Err: err, Op: "kv/scraper", @@ -49,27 +52,27 @@ func UnexpectedScrapersBucketError(err error) *influxdb.Error { // CorruptScraperError is used when the config cannot be unmarshalled from the // bytes stored in the kv. -func CorruptScraperError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func CorruptScraperError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("Unknown internal scraper data error; Err: %v", err), Op: "kv/scraper", } } // ErrUnprocessableScraper is used when a scraper is not able to be converted to JSON. -func ErrUnprocessableScraper(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, +func ErrUnprocessableScraper(err error) *errors.Error { + return &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: fmt.Sprintf("unable to convert scraper target into JSON; Err %v", err), } } // InternalScraperServiceError is used when the error comes from an // internal system. -func InternalScraperServiceError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func InternalScraperServiceError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("Unknown internal scraper data error; Err: %v", err), Op: "kv/scraper", } @@ -148,13 +151,13 @@ func (s *Service) listTargets(ctx context.Context, tx Tx, filter influxdb.Scrape } // AddTarget add a new scraper target into storage. -func (s *Service) AddTarget(ctx context.Context, target *influxdb.ScraperTarget, userID influxdb.ID) (err error) { +func (s *Service) AddTarget(ctx context.Context, target *influxdb.ScraperTarget, userID platform.ID) (err error) { return s.kv.Update(ctx, func(tx Tx) error { return s.addTarget(ctx, tx, target, userID) }) } -func (s *Service) addTarget(ctx context.Context, tx Tx, target *influxdb.ScraperTarget, userID influxdb.ID) error { +func (s *Service) addTarget(ctx context.Context, tx Tx, target *influxdb.ScraperTarget, userID platform.ID) error { if !target.OrgID.Valid() { return ErrInvalidScrapersOrgID } @@ -172,13 +175,13 @@ func (s *Service) addTarget(ctx context.Context, tx Tx, target *influxdb.Scraper } // RemoveTarget removes a scraper target from the bucket. -func (s *Service) RemoveTarget(ctx context.Context, id influxdb.ID) error { +func (s *Service) RemoveTarget(ctx context.Context, id platform.ID) error { return s.kv.Update(ctx, func(tx Tx) error { return s.removeTarget(ctx, tx, id) }) } -func (s *Service) removeTarget(ctx context.Context, tx Tx, id influxdb.ID) error { +func (s *Service) removeTarget(ctx context.Context, tx Tx, id platform.ID) error { _, pe := s.findTargetByID(ctx, tx, id) if pe != nil { return pe @@ -209,7 +212,7 @@ func (s *Service) removeTarget(ctx context.Context, tx Tx, id influxdb.ID) error } // UpdateTarget updates a scraper target. -func (s *Service) UpdateTarget(ctx context.Context, update *influxdb.ScraperTarget, userID influxdb.ID) (*influxdb.ScraperTarget, error) { +func (s *Service) UpdateTarget(ctx context.Context, update *influxdb.ScraperTarget, userID platform.ID) (*influxdb.ScraperTarget, error) { var target *influxdb.ScraperTarget err := s.kv.Update(ctx, func(tx Tx) error { var err error @@ -220,7 +223,7 @@ func (s *Service) UpdateTarget(ctx context.Context, update *influxdb.ScraperTarg return target, err } -func (s *Service) updateTarget(ctx context.Context, tx Tx, update *influxdb.ScraperTarget, userID influxdb.ID) (*influxdb.ScraperTarget, error) { +func (s *Service) updateTarget(ctx context.Context, tx Tx, update *influxdb.ScraperTarget, userID platform.ID) (*influxdb.ScraperTarget, error) { if !update.ID.Valid() { return nil, ErrInvalidScraperID } @@ -242,7 +245,7 @@ func (s *Service) updateTarget(ctx context.Context, tx Tx, update *influxdb.Scra } // GetTargetByID retrieves a scraper target by id. -func (s *Service) GetTargetByID(ctx context.Context, id influxdb.ID) (*influxdb.ScraperTarget, error) { +func (s *Service) GetTargetByID(ctx context.Context, id platform.ID) (*influxdb.ScraperTarget, error) { var target *influxdb.ScraperTarget err := s.kv.View(ctx, func(tx Tx) error { var err error @@ -253,7 +256,7 @@ func (s *Service) GetTargetByID(ctx context.Context, id influxdb.ID) (*influxdb. return target, err } -func (s *Service) findTargetByID(ctx context.Context, tx Tx, id influxdb.ID) (*influxdb.ScraperTarget, error) { +func (s *Service) findTargetByID(ctx context.Context, tx Tx, id platform.ID) (*influxdb.ScraperTarget, error) { encID, err := id.Encode() if err != nil { return nil, ErrInvalidScraperID diff --git a/kv/service.go b/kv/service.go index b317f1e1786..7ad86dfb77f 100644 --- a/kv/service.go +++ b/kv/service.go @@ -3,6 +3,7 @@ package kv import ( "github.com/benbjohnson/clock" "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" "github.com/influxdata/influxdb/v2/rand" "github.com/influxdata/influxdb/v2/resource" "github.com/influxdata/influxdb/v2/resource/noop" @@ -20,7 +21,7 @@ type Service struct { clock clock.Clock Config ServiceConfig audit resource.Logger - IDGenerator influxdb.IDGenerator + IDGenerator platform.IDGenerator // FluxLanguageService is used for parsing flux. // If this is unset, operations that require parsing flux diff --git a/kv/source.go b/kv/source.go index 7eed5630df6..c2062491eff 100644 --- a/kv/source.go +++ b/kv/source.go @@ -5,6 +5,9 @@ import ( "encoding/json" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + influxdb "github.com/influxdata/influxdb/v2" ) @@ -52,14 +55,14 @@ func (s *Service) DefaultSource(ctx context.Context) (*influxdb.Source, error) { return nil } } - return &influxdb.Error{ - Code: influxdb.ENotFound, + return &errors.Error{ + Code: errors.ENotFound, Msg: "no default source found", } }) if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -68,13 +71,13 @@ func (s *Service) DefaultSource(ctx context.Context) (*influxdb.Source, error) { } // FindSourceByID retrieves a source by id. -func (s *Service) FindSourceByID(ctx context.Context, id influxdb.ID) (*influxdb.Source, error) { +func (s *Service) FindSourceByID(ctx context.Context, id platform.ID) (*influxdb.Source, error) { var sr *influxdb.Source err := s.kv.View(ctx, func(tx Tx) error { src, pe := s.findSourceByID(ctx, tx, id) if pe != nil { - return &influxdb.Error{ + return &errors.Error{ Err: pe, } } @@ -84,10 +87,10 @@ func (s *Service) FindSourceByID(ctx context.Context, id influxdb.ID) (*influxdb return sr, err } -func (s *Service) findSourceByID(ctx context.Context, tx Tx, id influxdb.ID) (*influxdb.Source, error) { +func (s *Service) findSourceByID(ctx context.Context, tx Tx, id platform.ID) (*influxdb.Source, error) { encodedID, err := id.Encode() if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -99,8 +102,8 @@ func (s *Service) findSourceByID(ctx context.Context, tx Tx, id influxdb.ID) (*i v, err := b.Get(encodedID) if IsNotFound(err) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrSourceNotFound, } } @@ -115,7 +118,7 @@ func (s *Service) findSourceByID(ctx context.Context, tx Tx, id influxdb.ID) (*i var sr influxdb.Source if err := json.Unmarshal(v, &sr); err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -138,7 +141,7 @@ func (s *Service) FindSources(ctx context.Context, opt influxdb.FindOptions) ([] }) if err != nil { - return nil, 0, &influxdb.Error{ + return nil, 0, &errors.Error{ Op: influxdb.OpFindSources, Err: err, } @@ -175,7 +178,7 @@ func (s *Service) CreateSource(ctx context.Context, src *influxdb.Source) error return s.putSource(ctx, tx, src) }) if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -238,12 +241,12 @@ func (s *Service) forEachSource(ctx context.Context, tx Tx, fn func(*influxdb.So } // UpdateSource updates a source according the parameters set on upd. -func (s *Service) UpdateSource(ctx context.Context, id influxdb.ID, upd influxdb.SourceUpdate) (*influxdb.Source, error) { +func (s *Service) UpdateSource(ctx context.Context, id platform.ID, upd influxdb.SourceUpdate) (*influxdb.Source, error) { var sr *influxdb.Source err := s.kv.Update(ctx, func(tx Tx) error { src, err := s.updateSource(ctx, tx, id, upd) if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -254,7 +257,7 @@ func (s *Service) UpdateSource(ctx context.Context, id influxdb.ID, upd influxdb return sr, err } -func (s *Service) updateSource(ctx context.Context, tx Tx, id influxdb.ID, upd influxdb.SourceUpdate) (*influxdb.Source, error) { +func (s *Service) updateSource(ctx context.Context, tx Tx, id platform.ID, upd influxdb.SourceUpdate) (*influxdb.Source, error) { src, pe := s.findSourceByID(ctx, tx, id) if pe != nil { return nil, pe @@ -272,11 +275,11 @@ func (s *Service) updateSource(ctx context.Context, tx Tx, id influxdb.ID, upd i } // DeleteSource deletes a source and prunes it from the index. -func (s *Service) DeleteSource(ctx context.Context, id influxdb.ID) error { +func (s *Service) DeleteSource(ctx context.Context, id platform.ID) error { return s.kv.Update(ctx, func(tx Tx) error { pe := s.deleteSource(ctx, tx, id) if pe != nil { - return &influxdb.Error{ + return &errors.Error{ Err: pe, } } @@ -284,10 +287,10 @@ func (s *Service) DeleteSource(ctx context.Context, id influxdb.ID) error { }) } -func (s *Service) deleteSource(ctx context.Context, tx Tx, id influxdb.ID) error { +func (s *Service) deleteSource(ctx context.Context, tx Tx, id platform.ID) error { if id == DefaultSource.ID { - return &influxdb.Error{ - Code: influxdb.EForbidden, + return &errors.Error{ + Code: errors.EForbidden, Msg: "cannot delete autogen source", } } @@ -298,7 +301,7 @@ func (s *Service) deleteSource(ctx context.Context, tx Tx, id influxdb.ID) error encodedID, err := id.Encode() if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -309,7 +312,7 @@ func (s *Service) deleteSource(ctx context.Context, tx Tx, id influxdb.ID) error } if err = b.Delete(encodedID); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } diff --git a/kv/store_base.go b/kv/store_base.go index d4b99d6cf40..ab0f39ce9b6 100644 --- a/kv/store_base.go +++ b/kv/store_base.go @@ -6,7 +6,9 @@ import ( "errors" "fmt" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2/kit/tracing" "github.com/opentracing/opentracing-go" ) @@ -51,7 +53,7 @@ type DecodeBucketValFn func(key, val []byte) (keyRepeat []byte, decodedVal inter // DecIndexID decodes the bucket val into an influxdb.ID. func DecIndexID(key, val []byte) ([]byte, interface{}, error) { - var i influxdb.ID + var i platform.ID return key, i, i.Decode(val) } @@ -60,19 +62,19 @@ type ConvertValToEntFn func(k []byte, v interface{}) (Entity, error) // DecodeOrgNameKey decodes a raw bucket key into the organization id and name // used to create it. -func DecodeOrgNameKey(k []byte) (influxdb.ID, string, error) { - var orgID influxdb.ID - if err := orgID.Decode(k[:influxdb.IDLength]); err != nil { +func DecodeOrgNameKey(k []byte) (platform.ID, string, error) { + var orgID platform.ID + if err := orgID.Decode(k[:platform.IDLength]); err != nil { return 0, "", err } - return orgID, string(k[influxdb.IDLength:]), nil + return orgID, string(k[platform.IDLength:]), nil } // NewOrgNameKeyStore creates a store for an entity's unique index on organization id and name. // This is used throughout the kv pkg here to provide an entity uniquness by name within an org. func NewOrgNameKeyStore(resource string, bktName []byte, caseSensitive bool) *StoreBase { var decValToEntFn ConvertValToEntFn = func(k []byte, v interface{}) (Entity, error) { - id, ok := v.(influxdb.ID) + id, ok := v.(platform.ID) if err := IsErrUnexpectedDecodeVal(ok); err != nil { return Entity{}, err } @@ -299,8 +301,8 @@ func (s *StoreBase) Put(ctx context.Context, tx Tx, ent Entity, opts ...PutOptio var opt putOption for _, o := range opts { if err := o(&opt); err != nil { - return &influxdb.Error{ - Code: influxdb.EConflict, + return &errors2.Error{ + Code: errors2.EConflict, Err: err, } } @@ -333,9 +335,9 @@ func (s *StoreBase) putValidate(ctx context.Context, tx Tx, ent Entity, opt putO _, err := s.FindEnt(ctx, tx, ent) if opt.isNew { - if err == nil || influxdb.ErrorCode(err) != influxdb.ENotFound { - return &influxdb.Error{ - Code: influxdb.EConflict, + if err == nil || errors2.ErrorCode(err) != errors2.ENotFound { + return &errors2.Error{ + Code: errors2.EConflict, Msg: fmt.Sprintf("%s is not unique", s.Resource), Err: err, } @@ -351,8 +353,8 @@ func (s *StoreBase) bucket(ctx context.Context, tx Tx) (Bucket, error) { bkt, err := tx.Bucket(s.BktName) if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInternal, + return nil, &errors2.Error{ + Code: errors2.EInternal, Msg: fmt.Sprintf("unexpected error retrieving bucket %q; Err %v", string(s.BktName), err), Err: err, } @@ -371,8 +373,8 @@ func (s *StoreBase) bucketCursor(ctx context.Context, tx Tx) (Cursor, error) { cur, err := b.Cursor() if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInternal, + return nil, &errors2.Error{ + Code: errors2.EInternal, Msg: "failed to retrieve cursor", Err: err, } @@ -394,12 +396,12 @@ func (s *StoreBase) bucketDelete(ctx context.Context, tx Tx, key []byte) error { return nil } - iErr := &influxdb.Error{ - Code: influxdb.EInternal, + iErr := &errors2.Error{ + Code: errors2.EInternal, Err: err, } if IsNotFound(err) { - iErr.Code = influxdb.ENotFound + iErr.Code = errors2.ENotFound iErr.Msg = fmt.Sprintf("%s does exist for key: %q", s.Resource, string(key)) } return iErr @@ -416,14 +418,14 @@ func (s *StoreBase) bucketGet(ctx context.Context, tx Tx, key []byte) ([]byte, e body, err := b.Get(key) if IsNotFound(err) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors2.Error{ + Code: errors2.ENotFound, Msg: fmt.Sprintf("%s not found for key %q", s.Resource, string(key)), } } if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInternal, + return nil, &errors2.Error{ + Code: errors2.EInternal, Err: err, } } @@ -441,8 +443,8 @@ func (s *StoreBase) bucketPut(ctx context.Context, tx Tx, key, body []byte) erro } if err := b.Put(key, body); err != nil { - return &influxdb.Error{ - Code: influxdb.EInternal, + return &errors2.Error{ + Code: errors2.EInternal, Err: err, } } @@ -455,8 +457,8 @@ func (s *StoreBase) decodeEnt(ctx context.Context, body []byte) (interface{}, er _, v, err := s.DecodeEntFn([]byte{}, body) // ignore key here if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInternal, + return nil, &errors2.Error{ + Code: errors2.EInternal, Msg: fmt.Sprintf("failed to decode %s body", s.Resource), Err: err, } @@ -469,16 +471,16 @@ func (s *StoreBase) encodeEnt(ctx context.Context, ent Entity, fn EncodeEntFn) ( defer span.Finish() if fn == nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: fmt.Sprintf("no key was provided for %s", s.Resource), } } encoded, field, err := fn(ent) if err != nil { - return encoded, &influxdb.Error{ - Code: influxdb.EInvalid, + return encoded, &errors2.Error{ + Code: errors2.EInvalid, Msg: fmt.Sprintf("provided %s %s is an invalid format", s.Resource, field), Err: err, } diff --git a/kv/store_base_test.go b/kv/store_base_test.go index a3077024e01..0858da67bbf 100644 --- a/kv/store_base_test.go +++ b/kv/store_base_test.go @@ -4,10 +4,11 @@ import ( "context" "encoding/json" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "testing" "time" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" "github.com/influxdata/influxdb/v2/kv/migration" "github.com/stretchr/testify/assert" @@ -99,7 +100,7 @@ func TestStoreBase(t *testing.T) { return base.Put(context.TODO(), tx, entCopy, kv.PutNew()) }) require.Error(t, err) - assert.Equal(t, influxdb.EConflict, influxdb.ErrorCode(err)) + assert.Equal(t, errors.EConflict, errors.ErrorCode(err)) }) }) @@ -115,7 +116,7 @@ func TestStoreBase(t *testing.T) { return base.Put(context.TODO(), tx, entCopy, kv.PutUpdate()) }) require.Error(t, err) - assert.Equal(t, influxdb.ENotFound, influxdb.ErrorCode(err)) + assert.Equal(t, errors.ENotFound, errors.ErrorCode(err)) }) }) @@ -336,7 +337,7 @@ func testFind(t *testing.T, fn func(t *testing.T, suffix string) (storeBase, fun { name: "with id prefix", opts: kv.FindOpts{ - Prefix: encodeID(t, 3000000)[:influxdb.IDLength-5], + Prefix: encodeID(t, 3000000)[:platform.IDLength-5], }, expected: toIfaces(expectedEnts[2], expectedEnts[3]), }, @@ -366,8 +367,8 @@ func testFind(t *testing.T, fn func(t *testing.T, suffix string) (storeBase, fun } type foo struct { - ID influxdb.ID - OrgID influxdb.ID + ID platform.ID + OrgID platform.ID Name string } @@ -422,7 +423,7 @@ func getEntRaw(t *testing.T, kvStore kv.Store, bktName []byte, key []byte) []byt return actualRaw } -func encodeID(t *testing.T, id influxdb.ID) []byte { +func encodeID(t *testing.T, id platform.ID) []byte { t.Helper() b, err := id.Encode() @@ -450,7 +451,7 @@ func decFooEntFn(k []byte, v interface{}) (kv.Entity, error) { }, nil } -func newFooEnt(id, orgID influxdb.ID, name string) kv.Entity { +func newFooEnt(id, orgID platform.ID, name string) kv.Entity { f := foo{ID: id, Name: name, OrgID: orgID} return kv.Entity{ PK: kv.EncID(f.ID), @@ -462,11 +463,11 @@ func newFooEnt(id, orgID influxdb.ID, name string) kv.Entity { func isNotFoundErr(t *testing.T, err error) { t.Helper() - iErr, ok := err.(*influxdb.Error) + iErr, ok := err.(*errors.Error) if !ok { require.FailNowf(t, "expected an *influxdb.Error type", "got: %#v", err) } - assert.Equal(t, influxdb.ENotFound, iErr.Code) + assert.Equal(t, errors.ENotFound, iErr.Code) } func toIfaces(ents ...kv.Entity) []interface{} { diff --git a/kv/store_index.go b/kv/store_index.go index 82556207c13..23b8b5e0d37 100644 --- a/kv/store_index.go +++ b/kv/store_index.go @@ -6,7 +6,8 @@ import ( "errors" "fmt" - "github.com/influxdata/influxdb/v2" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + ierrors "github.com/influxdata/influxdb/v2/kit/errors" "github.com/influxdata/influxdb/v2/kit/tracing" ) @@ -81,8 +82,8 @@ func (s *IndexStore) FindEnt(ctx context.Context, tx Tx, ent Entity) (interface{ _, err := s.EntStore.EntKey(ctx, ent) if err != nil { if _, idxErr := s.IndexStore.EntKey(ctx, ent); idxErr != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: "no key was provided for " + s.Resource, } } @@ -123,8 +124,8 @@ func (s *IndexStore) Put(ctx context.Context, tx Tx, ent Entity, opts ...PutOpti var opt putOption for _, o := range opts { if err := o(&opt); err != nil { - return &influxdb.Error{ - Code: influxdb.EConflict, + return &errors2.Error{ + Code: errors2.EConflict, Err: err, } } @@ -153,18 +154,18 @@ func (s *IndexStore) putValidate(ctx context.Context, tx Tx, ent Entity, opt put func (s *IndexStore) validNew(ctx context.Context, tx Tx, ent Entity) error { _, err := s.IndexStore.FindEnt(ctx, tx, ent) - if err == nil || influxdb.ErrorCode(err) != influxdb.ENotFound { + if err == nil || errors2.ErrorCode(err) != errors2.ENotFound { key, _ := s.IndexStore.EntKey(ctx, ent) - return &influxdb.Error{ - Code: influxdb.EConflict, + return &errors2.Error{ + Code: errors2.EConflict, Msg: fmt.Sprintf("%s is not unique for key %s", s.Resource, string(key)), Err: err, } } _, err = s.EntStore.FindEnt(ctx, tx, ent) - if err == nil || influxdb.ErrorCode(err) != influxdb.ENotFound { - return &influxdb.Error{Code: influxdb.EConflict, Err: err} + if err == nil || errors2.ErrorCode(err) != errors2.ENotFound { + return &errors2.Error{Code: errors2.EConflict, Err: err} } return nil } @@ -197,7 +198,7 @@ func (s *IndexStore) validUpdate(ctx context.Context, tx Tx, ent Entity) (e erro idxVal, err := s.IndexStore.FindEnt(ctx, tx, ent) if err != nil { - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors2.ErrorCode(err) == errors2.ENotFound { return nil } return err @@ -214,17 +215,17 @@ func (s *IndexStore) validUpdate(ctx context.Context, tx Tx, ent Entity) (e erro } if err := sameKeys(ent.PK, indexEnt.PK); err != nil { - if _, err := s.EntStore.FindEnt(ctx, tx, ent); influxdb.ErrorCode(err) == influxdb.ENotFound { + if _, err := s.EntStore.FindEnt(ctx, tx, ent); errors2.ErrorCode(err) == errors2.ENotFound { key, _ := ent.PK() - return &influxdb.Error{ - Code: influxdb.ENotFound, + return &errors2.Error{ + Code: errors2.ENotFound, Msg: fmt.Sprintf("%s does not exist for key %s", s.Resource, string(key)), Err: err, } } key, _ := indexEnt.UniqueKey() - return &influxdb.Error{ - Code: influxdb.EConflict, + return &errors2.Error{ + Code: errors2.EConflict, Msg: fmt.Sprintf("%s entity update conflicts with an existing entity for key %s", s.Resource, string(key)), } } diff --git a/kv/store_index_test.go b/kv/store_index_test.go index 7765939af71..f366c769f75 100644 --- a/kv/store_index_test.go +++ b/kv/store_index_test.go @@ -2,9 +2,9 @@ package kv_test import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "testing" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" "github.com/influxdata/influxdb/v2/kv/migration" "github.com/stretchr/testify/assert" @@ -87,7 +87,7 @@ func TestIndexStore(t *testing.T) { return indexStore.Put(context.TODO(), tx, ent, kv.PutUpdate()) }) require.Error(t, err) - assert.Equal(t, influxdb.ENotFound, influxdb.ErrorCode(err)) + assert.Equal(t, errors.ENotFound, errors.ErrorCode(err)) }) t.Run("updating entity with no naming collision succeeds", func(t *testing.T) { @@ -140,7 +140,7 @@ func TestIndexStore(t *testing.T) { return indexStore.Put(context.TODO(), tx, entCopy, kv.PutNew()) }) require.Error(t, err) - assert.Equal(t, influxdb.EConflict, influxdb.ErrorCode(err)) + assert.Equal(t, errors.EConflict, errors.ErrorCode(err)) }) t.Run("updating entity that does not exist", func(t *testing.T) { @@ -160,7 +160,7 @@ func TestIndexStore(t *testing.T) { return indexStore.Put(context.TODO(), tx, entCopy, kv.PutUpdate()) }) require.Error(t, err) - assert.Equal(t, influxdb.ENotFound, influxdb.ErrorCode(err), "got: "+err.Error()) + assert.Equal(t, errors.ENotFound, errors.ErrorCode(err), "got: "+err.Error()) }) t.Run("updating entity that does collides with an existing entity", func(t *testing.T) { @@ -180,7 +180,7 @@ func TestIndexStore(t *testing.T) { return indexStore.Put(context.TODO(), tx, entCopy, kv.PutUpdate()) }) require.Error(t, err) - assert.Equal(t, influxdb.EConflict, influxdb.ErrorCode(err)) + assert.Equal(t, errors.EConflict, errors.ErrorCode(err)) assert.Contains(t, err.Error(), "update conflicts") }) }) diff --git a/kv/task.go b/kv/task.go index 52954d802b9..2ee241fcd13 100644 --- a/kv/task.go +++ b/kv/task.go @@ -8,6 +8,8 @@ import ( "strings" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" icontext "github.com/influxdata/influxdb/v2/context" "github.com/influxdata/influxdb/v2/resource" @@ -35,11 +37,11 @@ var ( var _ influxdb.TaskService = (*Service)(nil) type kvTask struct { - ID influxdb.ID `json:"id"` + ID platform.ID `json:"id"` Type string `json:"type,omitempty"` - OrganizationID influxdb.ID `json:"orgID"` + OrganizationID platform.ID `json:"orgID"` Organization string `json:"org"` - OwnerID influxdb.ID `json:"ownerID"` + OwnerID platform.ID `json:"ownerID"` Name string `json:"name"` Description string `json:"description,omitempty"` Status string `json:"status"` @@ -85,7 +87,7 @@ func kvToInfluxTask(k *kvTask) *influxdb.Task { } // FindTaskByID returns a single task -func (s *Service) FindTaskByID(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { +func (s *Service) FindTaskByID(ctx context.Context, id platform.ID) (*influxdb.Task, error) { var t *influxdb.Task err := s.kv.View(ctx, func(tx Tx) error { task, err := s.findTaskByID(ctx, tx, id) @@ -104,7 +106,7 @@ func (s *Service) FindTaskByID(ctx context.Context, id influxdb.ID) (*influxdb.T // findTaskByID is an internal method used to do any action with tasks internally // that do not require authorization. -func (s *Service) findTaskByID(ctx context.Context, tx Tx, id influxdb.ID) (*influxdb.Task, error) { +func (s *Service) findTaskByID(ctx context.Context, tx Tx, id platform.ID) (*influxdb.Task, error) { taskKey, err := taskKey(id) if err != nil { return nil, err @@ -253,10 +255,10 @@ func (s *Service) findTasksByUser(ctx context.Context, tx Tx, filter influxdb.Ta } // findTasksByOrg is a subset of the find tasks function. Used for cleanliness -func (s *Service) findTasksByOrg(ctx context.Context, tx Tx, orgID influxdb.ID, filter influxdb.TaskFilter) ([]*influxdb.Task, int, error) { +func (s *Service) findTasksByOrg(ctx context.Context, tx Tx, orgID platform.ID, filter influxdb.TaskFilter) ([]*influxdb.Task, int, error) { var err error if !orgID.Valid() { - return nil, 0, fmt.Errorf("finding tasks by organization ID: %w", influxdb.ErrInvalidID) + return nil, 0, fmt.Errorf("finding tasks by organization ID: %w", platform.ErrInvalidID) } var ts []*influxdb.Task @@ -299,7 +301,7 @@ func (s *Service) findTasksByOrg(ctx context.Context, tx Tx, orgID influxdb.ID, matchFn := newTaskMatchFn(filter, nil) for k, v := c.Next(); k != nil; k, v = c.Next() { - id, err := influxdb.IDFromString(string(v)) + id, err := platform.IDFromString(string(v)) if err != nil { return nil, 0, influxdb.ErrInvalidTaskID } @@ -574,7 +576,7 @@ func (s *Service) createTask(ctx context.Context, tx Tx, org *influxdb.Organizat } // UpdateTask updates a single task with changeset. -func (s *Service) UpdateTask(ctx context.Context, id influxdb.ID, upd influxdb.TaskUpdate) (*influxdb.Task, error) { +func (s *Service) UpdateTask(ctx context.Context, id platform.ID, upd influxdb.TaskUpdate) (*influxdb.Task, error) { var t *influxdb.Task err := s.kv.Update(ctx, func(tx Tx) error { task, err := s.updateTask(ctx, tx, id, upd) @@ -591,7 +593,7 @@ func (s *Service) UpdateTask(ctx context.Context, id influxdb.ID, upd influxdb.T return t, nil } -func (s *Service) updateTask(ctx context.Context, tx Tx, id influxdb.ID, upd influxdb.TaskUpdate) (*influxdb.Task, error) { +func (s *Service) updateTask(ctx context.Context, tx Tx, id platform.ID, upd influxdb.TaskUpdate) (*influxdb.Task, error) { // retrieve the task task, err := s.findTaskByID(ctx, tx, id) if err != nil { @@ -731,7 +733,7 @@ func (s *Service) updateTask(ctx context.Context, tx Tx, id influxdb.ID, upd inf } // DeleteTask removes a task by ID and purges all associated data and scheduled runs. -func (s *Service) DeleteTask(ctx context.Context, id influxdb.ID) error { +func (s *Service) DeleteTask(ctx context.Context, id platform.ID) error { err := s.kv.Update(ctx, func(tx Tx) error { err := s.deleteTask(ctx, tx, id) if err != nil { @@ -746,7 +748,7 @@ func (s *Service) DeleteTask(ctx context.Context, id influxdb.ID) error { return nil } -func (s *Service) deleteTask(ctx context.Context, tx Tx, id influxdb.ID) error { +func (s *Service) deleteTask(ctx context.Context, tx Tx, id platform.ID) error { taskBucket, err := tx.Bucket(taskBucket) if err != nil { return influxdb.ErrUnexpectedTaskBucketErr(err) @@ -945,7 +947,7 @@ func (s *Service) findRuns(ctx context.Context, tx Tx, filter influxdb.RunFilter } // FindRunByID returns a single run. -func (s *Service) FindRunByID(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (s *Service) FindRunByID(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { var run *influxdb.Run err := s.kv.View(ctx, func(tx Tx) error { r, err := s.findRunByID(ctx, tx, taskID, runID) @@ -962,7 +964,7 @@ func (s *Service) FindRunByID(ctx context.Context, taskID, runID influxdb.ID) (* return run, nil } -func (s *Service) findRunByID(ctx context.Context, tx Tx, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (s *Service) findRunByID(ctx context.Context, tx Tx, taskID, runID platform.ID) (*influxdb.Run, error) { bucket, err := tx.Bucket(taskRunBucket) if err != nil { return nil, influxdb.ErrUnexpectedTaskBucketErr(err) @@ -989,7 +991,7 @@ func (s *Service) findRunByID(ctx context.Context, tx Tx, taskID, runID influxdb } // CancelRun cancels a currently running run. -func (s *Service) CancelRun(ctx context.Context, taskID, runID influxdb.ID) error { +func (s *Service) CancelRun(ctx context.Context, taskID, runID platform.ID) error { err := s.kv.Update(ctx, func(tx Tx) error { err := s.cancelRun(ctx, tx, taskID, runID) if err != nil { @@ -1000,7 +1002,7 @@ func (s *Service) CancelRun(ctx context.Context, taskID, runID influxdb.ID) erro return err } -func (s *Service) cancelRun(ctx context.Context, tx Tx, taskID, runID influxdb.ID) error { +func (s *Service) cancelRun(ctx context.Context, tx Tx, taskID, runID platform.ID) error { // get the run run, err := s.findRunByID(ctx, tx, taskID, runID) if err != nil { @@ -1034,7 +1036,7 @@ func (s *Service) cancelRun(ctx context.Context, tx Tx, taskID, runID influxdb.I } // RetryRun creates and returns a new run (which is a retry of another run). -func (s *Service) RetryRun(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (s *Service) RetryRun(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { var r *influxdb.Run err := s.kv.Update(ctx, func(tx Tx) error { run, err := s.retryRun(ctx, tx, taskID, runID) @@ -1047,7 +1049,7 @@ func (s *Service) RetryRun(ctx context.Context, taskID, runID influxdb.ID) (*inf return r, err } -func (s *Service) retryRun(ctx context.Context, tx Tx, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (s *Service) retryRun(ctx context.Context, tx Tx, taskID, runID platform.ID) (*influxdb.Run, error) { // find the run r, err := s.findRunByID(ctx, tx, taskID, runID) if err != nil { @@ -1104,7 +1106,7 @@ func (s *Service) retryRun(ctx context.Context, tx Tx, taskID, runID influxdb.ID // ForceRun forces a run to occur with unix timestamp scheduledFor, to be executed as soon as possible. // The value of scheduledFor may or may not align with the task's schedule. -func (s *Service) ForceRun(ctx context.Context, taskID influxdb.ID, scheduledFor int64) (*influxdb.Run, error) { +func (s *Service) ForceRun(ctx context.Context, taskID platform.ID, scheduledFor int64) (*influxdb.Run, error) { var r *influxdb.Run err := s.kv.Update(ctx, func(tx Tx) error { run, err := s.forceRun(ctx, tx, taskID, scheduledFor) @@ -1117,7 +1119,7 @@ func (s *Service) ForceRun(ctx context.Context, taskID influxdb.ID, scheduledFor return r, err } -func (s *Service) forceRun(ctx context.Context, tx Tx, taskID influxdb.ID, scheduledFor int64) (*influxdb.Run, error) { +func (s *Service) forceRun(ctx context.Context, tx Tx, taskID platform.ID, scheduledFor int64) (*influxdb.Run, error) { // create a run t := time.Unix(scheduledFor, 0).UTC() r := &influxdb.Run{ @@ -1167,7 +1169,7 @@ func (s *Service) forceRun(ctx context.Context, tx Tx, taskID influxdb.ID, sched } // CreateRun creates a run with a scheduledFor time as now. -func (s *Service) CreateRun(ctx context.Context, taskID influxdb.ID, scheduledFor time.Time, runAt time.Time) (*influxdb.Run, error) { +func (s *Service) CreateRun(ctx context.Context, taskID platform.ID, scheduledFor time.Time, runAt time.Time) (*influxdb.Run, error) { var r *influxdb.Run err := s.kv.Update(ctx, func(tx Tx) error { run, err := s.createRun(ctx, tx, taskID, scheduledFor, runAt) @@ -1179,7 +1181,7 @@ func (s *Service) CreateRun(ctx context.Context, taskID influxdb.ID, scheduledFo }) return r, err } -func (s *Service) createRun(ctx context.Context, tx Tx, taskID influxdb.ID, scheduledFor time.Time, runAt time.Time) (*influxdb.Run, error) { +func (s *Service) createRun(ctx context.Context, tx Tx, taskID platform.ID, scheduledFor time.Time, runAt time.Time) (*influxdb.Run, error) { id := s.IDGenerator.ID() t := time.Unix(scheduledFor.Unix(), 0).UTC() @@ -1213,7 +1215,7 @@ func (s *Service) createRun(ctx context.Context, tx Tx, taskID influxdb.ID, sche return &run, nil } -func (s *Service) CurrentlyRunning(ctx context.Context, taskID influxdb.ID) ([]*influxdb.Run, error) { +func (s *Service) CurrentlyRunning(ctx context.Context, taskID platform.ID) ([]*influxdb.Run, error) { var runs []*influxdb.Run err := s.kv.View(ctx, func(tx Tx) error { rs, err := s.currentlyRunning(ctx, tx, taskID) @@ -1230,7 +1232,7 @@ func (s *Service) CurrentlyRunning(ctx context.Context, taskID influxdb.ID) ([]* return runs, nil } -func (s *Service) currentlyRunning(ctx context.Context, tx Tx, taskID influxdb.ID) ([]*influxdb.Run, error) { +func (s *Service) currentlyRunning(ctx context.Context, tx Tx, taskID platform.ID) ([]*influxdb.Run, error) { bucket, err := tx.Bucket(taskRunBucket) if err != nil { return nil, influxdb.ErrUnexpectedTaskBucketErr(err) @@ -1271,7 +1273,7 @@ func (s *Service) currentlyRunning(ctx context.Context, tx Tx, taskID influxdb.I return runs, nil } -func (s *Service) ManualRuns(ctx context.Context, taskID influxdb.ID) ([]*influxdb.Run, error) { +func (s *Service) ManualRuns(ctx context.Context, taskID platform.ID) ([]*influxdb.Run, error) { var runs []*influxdb.Run err := s.kv.View(ctx, func(tx Tx) error { rs, err := s.manualRuns(ctx, tx, taskID) @@ -1288,7 +1290,7 @@ func (s *Service) ManualRuns(ctx context.Context, taskID influxdb.ID) ([]*influx return runs, nil } -func (s *Service) manualRuns(ctx context.Context, tx Tx, taskID influxdb.ID) ([]*influxdb.Run, error) { +func (s *Service) manualRuns(ctx context.Context, tx Tx, taskID platform.ID) ([]*influxdb.Run, error) { b, err := tx.Bucket(taskRunBucket) if err != nil { return nil, influxdb.ErrUnexpectedTaskBucketErr(err) @@ -1312,7 +1314,7 @@ func (s *Service) manualRuns(ctx context.Context, tx Tx, taskID influxdb.ID) ([] return runs, nil } -func (s *Service) StartManualRun(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (s *Service) StartManualRun(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { var r *influxdb.Run err := s.kv.Update(ctx, func(tx Tx) error { run, err := s.startManualRun(ctx, tx, taskID, runID) @@ -1325,7 +1327,7 @@ func (s *Service) StartManualRun(ctx context.Context, taskID, runID influxdb.ID) return r, err } -func (s *Service) startManualRun(ctx context.Context, tx Tx, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (s *Service) startManualRun(ctx context.Context, tx Tx, taskID, runID platform.ID) (*influxdb.Run, error) { mRuns, err := s.manualRuns(ctx, tx, taskID) if err != nil { @@ -1386,7 +1388,7 @@ func (s *Service) startManualRun(ctx context.Context, tx Tx, taskID, runID influ } // FinishRun removes runID from the list of running tasks and if its `now` is later then last completed update it. -func (s *Service) FinishRun(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (s *Service) FinishRun(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { var run *influxdb.Run err := s.kv.Update(ctx, func(tx Tx) error { r, err := s.finishRun(ctx, tx, taskID, runID) @@ -1399,7 +1401,7 @@ func (s *Service) FinishRun(ctx context.Context, taskID, runID influxdb.ID) (*in return run, err } -func (s *Service) finishRun(ctx context.Context, tx Tx, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (s *Service) finishRun(ctx context.Context, tx Tx, taskID, runID platform.ID) (*influxdb.Run, error) { // get the run r, err := s.findRunByID(ctx, tx, taskID, runID) if err != nil { @@ -1456,7 +1458,7 @@ func (s *Service) finishRun(ctx context.Context, tx Tx, taskID, runID influxdb.I } // UpdateRunState sets the run state at the respective time. -func (s *Service) UpdateRunState(ctx context.Context, taskID, runID influxdb.ID, when time.Time, state influxdb.RunStatus) error { +func (s *Service) UpdateRunState(ctx context.Context, taskID, runID platform.ID, when time.Time, state influxdb.RunStatus) error { err := s.kv.Update(ctx, func(tx Tx) error { err := s.updateRunState(ctx, tx, taskID, runID, when, state) if err != nil { @@ -1467,7 +1469,7 @@ func (s *Service) UpdateRunState(ctx context.Context, taskID, runID influxdb.ID, return err } -func (s *Service) updateRunState(ctx context.Context, tx Tx, taskID, runID influxdb.ID, when time.Time, state influxdb.RunStatus) error { +func (s *Service) updateRunState(ctx context.Context, tx Tx, taskID, runID platform.ID, when time.Time, state influxdb.RunStatus) error { // find run run, err := s.findRunByID(ctx, tx, taskID, runID) if err != nil { @@ -1506,7 +1508,7 @@ func (s *Service) updateRunState(ctx context.Context, tx Tx, taskID, runID influ } // AddRunLog adds a log line to the run. -func (s *Service) AddRunLog(ctx context.Context, taskID, runID influxdb.ID, when time.Time, log string) error { +func (s *Service) AddRunLog(ctx context.Context, taskID, runID platform.ID, when time.Time, log string) error { err := s.kv.Update(ctx, func(tx Tx) error { err := s.addRunLog(ctx, tx, taskID, runID, when, log) if err != nil { @@ -1517,7 +1519,7 @@ func (s *Service) AddRunLog(ctx context.Context, taskID, runID influxdb.ID, when return err } -func (s *Service) addRunLog(ctx context.Context, tx Tx, taskID, runID influxdb.ID, when time.Time, log string) error { +func (s *Service) addRunLog(ctx context.Context, tx Tx, taskID, runID platform.ID, when time.Time, log string) error { // find run run, err := s.findRunByID(ctx, tx, taskID, runID) if err != nil { @@ -1549,7 +1551,7 @@ func (s *Service) addRunLog(ctx context.Context, tx Tx, taskID, runID influxdb.I return nil } -func taskKey(taskID influxdb.ID) ([]byte, error) { +func taskKey(taskID platform.ID) ([]byte, error) { encodedID, err := taskID.Encode() if err != nil { return nil, influxdb.ErrInvalidTaskID @@ -1557,7 +1559,7 @@ func taskKey(taskID influxdb.ID) ([]byte, error) { return encodedID, nil } -func taskLatestCompletedKey(taskID influxdb.ID) ([]byte, error) { +func taskLatestCompletedKey(taskID platform.ID) ([]byte, error) { encodedID, err := taskID.Encode() if err != nil { return nil, influxdb.ErrInvalidTaskID @@ -1565,7 +1567,7 @@ func taskLatestCompletedKey(taskID influxdb.ID) ([]byte, error) { return []byte(string(encodedID) + "/latestCompleted"), nil } -func taskManualRunKey(taskID influxdb.ID) ([]byte, error) { +func taskManualRunKey(taskID platform.ID) ([]byte, error) { encodedID, err := taskID.Encode() if err != nil { return nil, influxdb.ErrInvalidTaskID @@ -1573,7 +1575,7 @@ func taskManualRunKey(taskID influxdb.ID) ([]byte, error) { return []byte(string(encodedID) + "/manualRuns"), nil } -func taskOrgKey(orgID, taskID influxdb.ID) ([]byte, error) { +func taskOrgKey(orgID, taskID platform.ID) ([]byte, error) { encodedOrgID, err := orgID.Encode() if err != nil { return nil, influxdb.ErrInvalidTaskID @@ -1586,7 +1588,7 @@ func taskOrgKey(orgID, taskID influxdb.ID) ([]byte, error) { return []byte(string(encodedOrgID) + "/" + string(encodedID)), nil } -func taskRunKey(taskID, runID influxdb.ID) ([]byte, error) { +func taskRunKey(taskID, runID platform.ID) ([]byte, error) { encodedID, err := taskID.Encode() if err != nil { return nil, influxdb.ErrInvalidTaskID diff --git a/kv/task_private_test.go b/kv/task_private_test.go index 731a0430ed1..3aea01ec797 100644 --- a/kv/task_private_test.go +++ b/kv/task_private_test.go @@ -3,6 +3,8 @@ package kv import ( "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" ) @@ -17,12 +19,12 @@ func Test_newTaskMatchFN(t *testing.T) { } const ( - NoOrg = influxdb.ID(0) + NoOrg = platform.ID(0) NoTyp = "-" NoNam = "-" ) - newMatch := func(orgID influxdb.ID, typ string, name string) taskMatchFn { + newMatch := func(orgID platform.ID, typ string, name string) taskMatchFn { var ( org *influxdb.Organization fil influxdb.TaskFilter diff --git a/kv/task_test.go b/kv/task_test.go index 151389cc6af..baa647558cf 100644 --- a/kv/task_test.go +++ b/kv/task_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "github.com/influxdata/influxdb/v2/kit/platform" "testing" "time" @@ -169,7 +170,7 @@ func TestRetrieveTaskWithBadAuth(t *testing.T) { if err != nil { return err } - task.OwnerID = influxdb.ID(1) + task.OwnerID = platform.ID(1) tbyte, err := json.Marshal(task) if err != nil { return err diff --git a/kv/variable.go b/kv/variable.go index 19f6028fbf6..3c9deb9a0eb 100644 --- a/kv/variable.go +++ b/kv/variable.go @@ -5,6 +5,9 @@ import ( "encoding/json" "strings" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) @@ -15,34 +18,34 @@ var ( variableOrgsIndex = []byte("variableorgsv1") ) -func decodeVariableOrgsIndexKey(indexKey []byte) (orgID influxdb.ID, variableID influxdb.ID, err error) { - if len(indexKey) != 2*influxdb.IDLength { - return 0, 0, &influxdb.Error{ - Code: influxdb.EInvalid, +func decodeVariableOrgsIndexKey(indexKey []byte) (orgID platform.ID, variableID platform.ID, err error) { + if len(indexKey) != 2*platform.IDLength { + return 0, 0, &errors.Error{ + Code: errors.EInvalid, Msg: "malformed variable orgs index key (please report this error)", } } - if err := (&orgID).Decode(indexKey[:influxdb.IDLength]); err != nil { - return 0, 0, &influxdb.Error{ - Code: influxdb.EInvalid, + if err := (&orgID).Decode(indexKey[:platform.IDLength]); err != nil { + return 0, 0, &errors.Error{ + Code: errors.EInvalid, Msg: "bad org id", - Err: influxdb.ErrInvalidID, + Err: platform.ErrInvalidID, } } - if err := (&variableID).Decode(indexKey[influxdb.IDLength:]); err != nil { - return 0, 0, &influxdb.Error{ - Code: influxdb.EInvalid, + if err := (&variableID).Decode(indexKey[platform.IDLength:]); err != nil { + return 0, 0, &errors.Error{ + Code: errors.EInvalid, Msg: "bad variable id", - Err: influxdb.ErrInvalidID, + Err: platform.ErrInvalidID, } } return orgID, variableID, nil } -func (s *Service) findOrganizationVariables(ctx context.Context, tx Tx, orgID influxdb.ID) ([]*influxdb.Variable, error) { +func (s *Service) findOrganizationVariables(ctx context.Context, tx Tx, orgID platform.ID) ([]*influxdb.Variable, error) { idx, err := tx.Bucket(variableOrgsIndex) if err != nil { return nil, err @@ -166,7 +169,7 @@ func (s *Service) FindVariables(ctx context.Context, filter influxdb.VariableFil res := []*influxdb.Variable{} err := s.kv.View(ctx, func(tx Tx) error { variables, err := s.findVariables(ctx, tx, filter, opt...) - if err != nil && influxdb.ErrorCode(err) != influxdb.ENotFound { + if err != nil && errors.ErrorCode(err) != errors.ENotFound { return err } res = variables @@ -176,7 +179,7 @@ func (s *Service) FindVariables(ctx context.Context, filter influxdb.VariableFil } // FindVariableByID finds a single variable in the store by its ID -func (s *Service) FindVariableByID(ctx context.Context, id influxdb.ID) (*influxdb.Variable, error) { +func (s *Service) FindVariableByID(ctx context.Context, id platform.ID) (*influxdb.Variable, error) { var variable *influxdb.Variable err := s.kv.View(ctx, func(tx Tx) error { m, err := s.findVariableByID(ctx, tx, id) @@ -189,7 +192,7 @@ func (s *Service) FindVariableByID(ctx context.Context, id influxdb.ID) (*influx return variable, err } -func (s *Service) findVariableByID(ctx context.Context, tx Tx, id influxdb.ID) (*influxdb.Variable, error) { +func (s *Service) findVariableByID(ctx context.Context, tx Tx, id platform.ID) (*influxdb.Variable, error) { body, err := s.variableStore.FindEnt(ctx, tx, Entity{PK: EncID(id)}) if err != nil { return nil, err @@ -203,8 +206,8 @@ func (s *Service) findVariableByID(ctx context.Context, tx Tx, id influxdb.ID) ( func (s *Service) CreateVariable(ctx context.Context, v *influxdb.Variable) error { return s.kv.Update(ctx, func(tx Tx) error { if err := v.Valid(); err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -241,7 +244,7 @@ func (s *Service) putVariable(ctx context.Context, tx Tx, v *influxdb.Variable, } // UpdateVariable updates a single variable in the store with a changeset -func (s *Service) UpdateVariable(ctx context.Context, id influxdb.ID, update *influxdb.VariableUpdate) (*influxdb.Variable, error) { +func (s *Service) UpdateVariable(ctx context.Context, id platform.ID, update *influxdb.VariableUpdate) (*influxdb.Variable, error) { var v *influxdb.Variable err := s.kv.Update(ctx, func(tx Tx) error { m, err := s.findVariableByID(ctx, tx, id) @@ -262,7 +265,7 @@ func (s *Service) UpdateVariable(ctx context.Context, id influxdb.ID, update *in } // DeleteVariable removes a single variable from the store by its ID -func (s *Service) DeleteVariable(ctx context.Context, id influxdb.ID) error { +func (s *Service) DeleteVariable(ctx context.Context, id platform.ID) error { return s.kv.Update(ctx, func(tx Tx) error { v, err := s.findVariableByID(ctx, tx, id) if err != nil { @@ -279,7 +282,7 @@ func (s *Service) DeleteVariable(ctx context.Context, id influxdb.ID) error { func encodeVariableOrgsIndex(variable *influxdb.Variable) ([]byte, error) { oID, err := variable.OrganizationID.Encode() if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, Msg: "bad organization id", } @@ -287,13 +290,13 @@ func encodeVariableOrgsIndex(variable *influxdb.Variable) ([]byte, error) { mID, err := variable.ID.Encode() if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, Msg: "bad variable id", } } - key := make([]byte, 0, influxdb.IDLength*2) + key := make([]byte, 0, platform.IDLength*2) key = append(key, oID...) key = append(key, mID...) @@ -308,11 +311,11 @@ func (s *Service) putVariableOrgsIndex(tx Tx, variable *influxdb.Variable) error idx, err := tx.Bucket(variableOrgsIndex) if err != nil { - return &influxdb.Error{Code: influxdb.EInternal, Err: err} + return &errors.Error{Code: errors.EInternal, Err: err} } if err := idx.Put(key, nil); err != nil { - return &influxdb.Error{Code: influxdb.EInternal, Err: err} + return &errors.Error{Code: errors.EInternal, Err: err} } return nil @@ -326,11 +329,11 @@ func (s *Service) removeVariableOrgsIndex(tx Tx, variable *influxdb.Variable) er idx, err := tx.Bucket(variableOrgsIndex) if err != nil { - return &influxdb.Error{Code: influxdb.EInternal, Err: err} + return &errors.Error{Code: errors.EInternal, Err: err} } if err := idx.Delete(key); err != nil { - return &influxdb.Error{Code: influxdb.EInternal, Err: err} + return &errors.Error{Code: errors.EInternal, Err: err} } return nil diff --git a/label.go b/label.go index 90fe947dfe0..1447d3f10b1 100644 --- a/label.go +++ b/label.go @@ -2,6 +2,9 @@ package influxdb import ( "context" + + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) // ErrLabelNotFound is the error for a missing Label. @@ -21,15 +24,15 @@ const ( // errors on label var ( // ErrLabelNameisEmpty is error when org name is empty - ErrLabelNameisEmpty = &Error{ - Code: EInvalid, + ErrLabelNameisEmpty = &errors.Error{ + Code: errors.EInvalid, Msg: "label name is empty", } // ErrLabelExistsOnResource is used when attempting to add a label to a resource // when that label already exists on the resource - ErrLabelExistsOnResource = &Error{ - Code: EConflict, + ErrLabelExistsOnResource = &errors.Error{ + Code: errors.EConflict, Msg: "Cannot add label, label already exists on resource", } ) @@ -37,7 +40,7 @@ var ( // LabelService represents a service for managing resource labels type LabelService interface { // FindLabelByID a single label by ID. - FindLabelByID(ctx context.Context, id ID) (*Label, error) + FindLabelByID(ctx context.Context, id platform.ID) (*Label, error) // FindLabels returns a list of labels that match a filter FindLabels(ctx context.Context, filter LabelFilter, opt ...FindOptions) ([]*Label, error) @@ -52,10 +55,10 @@ type LabelService interface { CreateLabelMapping(ctx context.Context, m *LabelMapping) error // UpdateLabel updates a label with a changeset. - UpdateLabel(ctx context.Context, id ID, upd LabelUpdate) (*Label, error) + UpdateLabel(ctx context.Context, id platform.ID, upd LabelUpdate) (*Label, error) // DeleteLabel deletes a label - DeleteLabel(ctx context.Context, id ID) error + DeleteLabel(ctx context.Context, id platform.ID) error // DeleteLabelMapping deletes a label mapping DeleteLabelMapping(ctx context.Context, m *LabelMapping) error @@ -63,8 +66,8 @@ type LabelService interface { // Label is a tag set on a resource, typically used for filtering on a UI. type Label struct { - ID ID `json:"id,omitempty"` - OrgID ID `json:"orgID,omitempty"` + ID platform.ID `json:"id,omitempty"` + OrgID platform.ID `json:"orgID,omitempty"` Name string `json:"name"` Properties map[string]string `json:"properties,omitempty"` } @@ -72,15 +75,15 @@ type Label struct { // Validate returns an error if the label is invalid. func (l *Label) Validate() error { if l.Name == "" { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "label name is required", } } if !l.OrgID.Valid() { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "orgID is required", } } @@ -91,28 +94,28 @@ func (l *Label) Validate() error { // LabelMapping is used to map resource to its labels. // It should not be shared directly over the HTTP API. type LabelMapping struct { - LabelID ID `json:"labelID"` - ResourceID ID `json:"resourceID,omitempty"` + LabelID platform.ID `json:"labelID"` + ResourceID platform.ID `json:"resourceID,omitempty"` ResourceType `json:"resourceType"` } // Validate returns an error if the mapping is invalid. func (l *LabelMapping) Validate() error { if !l.LabelID.Valid() { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "label id is required", } } if !l.ResourceID.Valid() { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "resource id is required", } } if err := l.ResourceType.Valid(); err != nil { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -130,11 +133,11 @@ type LabelUpdate struct { // LabelFilter represents a set of filters that restrict the returned results. type LabelFilter struct { Name string - OrgID *ID + OrgID *platform.ID } // LabelMappingFilter represents a set of filters that restrict the returned results. type LabelMappingFilter struct { - ResourceID ID + ResourceID platform.ID ResourceType } diff --git a/label/error.go b/label/error.go index 668b9141726..b71999e59d3 100644 --- a/label/error.go +++ b/label/error.go @@ -1,34 +1,34 @@ package label import ( - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) var ( // NotUniqueIDError occurs when attempting to create a Label with an ID that already belongs to another one - NotUniqueIDError = &influxdb.Error{ - Code: influxdb.EConflict, + NotUniqueIDError = &errors.Error{ + Code: errors.EConflict, Msg: "ID already exists", } // ErrFailureGeneratingID occurs ony when the random number generator // cannot generate an ID in MaxIDGenerationN times. - ErrFailureGeneratingID = &influxdb.Error{ - Code: influxdb.EInternal, + ErrFailureGeneratingID = &errors.Error{ + Code: errors.EInternal, Msg: "unable to generate valid id", } // ErrLabelNotFound occurs when a label cannot be found by its ID - ErrLabelNotFound = &influxdb.Error{ - Code: influxdb.ENotFound, + ErrLabelNotFound = &errors.Error{ + Code: errors.ENotFound, Msg: "label not found", } ) // ErrInternalServiceError is used when the error comes from an internal system. -func ErrInternalServiceError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func ErrInternalServiceError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Err: err, } } diff --git a/label/http_client.go b/label/http_client.go index ad5b83af482..b47c63a74cd 100644 --- a/label/http_client.go +++ b/label/http_client.go @@ -4,6 +4,8 @@ import ( "context" "path" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/pkg/httpc" ) @@ -14,15 +16,15 @@ type LabelClientService struct { Client *httpc.Client } -func labelIDPath(id influxdb.ID) string { +func labelIDPath(id platform.ID) string { return path.Join(prefixLabels, id.String()) } -func resourceIDPath(resourceType influxdb.ResourceType, resourceID influxdb.ID, p string) string { +func resourceIDPath(resourceType influxdb.ResourceType, resourceID platform.ID, p string) string { return path.Join("/api/v2/", string(resourceType), resourceID.String(), p) } -func resourceIDMappingPath(resourceType influxdb.ResourceType, resourceID influxdb.ID, p string, labelID influxdb.ID) string { +func resourceIDMappingPath(resourceType influxdb.ResourceType, resourceID platform.ID, p string, labelID platform.ID) string { return path.Join("/api/v2/", string(resourceType), resourceID.String(), p, labelID.String()) } @@ -42,7 +44,7 @@ func (s *LabelClientService) CreateLabel(ctx context.Context, l *influxdb.Label) } // FindLabelByID returns a single label by ID. -func (s *LabelClientService) FindLabelByID(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { +func (s *LabelClientService) FindLabelByID(ctx context.Context, id platform.ID) (*influxdb.Label, error) { var lr labelResponse err := s.Client. Get(labelIDPath(id)). @@ -94,7 +96,7 @@ func (s *LabelClientService) FindResourceLabels(ctx context.Context, filter infl } // UpdateLabel updates a label and returns the updated label. -func (s *LabelClientService) UpdateLabel(ctx context.Context, id influxdb.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { +func (s *LabelClientService) UpdateLabel(ctx context.Context, id platform.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { var lr labelResponse err := s.Client. PatchJSON(upd, labelIDPath(id)). @@ -107,7 +109,7 @@ func (s *LabelClientService) UpdateLabel(ctx context.Context, id influxdb.ID, up } // DeleteLabel removes a label by ID. -func (s *LabelClientService) DeleteLabel(ctx context.Context, id influxdb.ID) error { +func (s *LabelClientService) DeleteLabel(ctx context.Context, id platform.ID) error { return s.Client. Delete(labelIDPath(id)). Do(ctx) diff --git a/label/http_handler.go b/label/http_handler.go index 640a9912867..3875d474bc1 100644 --- a/label/http_handler.go +++ b/label/http_handler.go @@ -5,6 +5,9 @@ import ( "fmt" "net/http" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/influxdata/influxdb/v2" @@ -31,14 +34,14 @@ func NewHTTPEmbeddedHandler(log *zap.Logger, rt influxdb.ResourceType, ls influx r := chi.NewRouter() r.NotFound(func(w http.ResponseWriter, r *http.Request) { - h.api.Err(w, r, &influxdb.Error{ - Code: influxdb.ENotFound, + h.api.Err(w, r, &errors.Error{ + Code: errors.ENotFound, Msg: "path not found", }) }) r.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) { - h.api.Err(w, r, &influxdb.Error{ - Code: influxdb.EMethodNotAllowed, + h.api.Err(w, r, &errors.Error{ + Code: errors.EMethodNotAllowed, Msg: fmt.Sprintf("allow: %s", w.Header().Get("Allow")), }) @@ -66,7 +69,7 @@ func NewHTTPEmbeddedHandler(log *zap.Logger, rt influxdb.ResourceType, ls influx func (h *LabelEmbeddedHandler) handlePostLabelMapping(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - embeddedID, err := influxdb.IDFromString(chi.URLParam(r, "id")) + embeddedID, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { h.api.Err(w, r, err) return @@ -74,8 +77,8 @@ func (h *LabelEmbeddedHandler) handlePostLabelMapping(w http.ResponseWriter, r * mapping := &influxdb.LabelMapping{} if err := json.NewDecoder(r.Body).Decode(mapping); err != nil { - h.api.Err(w, r, &influxdb.Error{ - Code: influxdb.EInvalid, + h.api.Err(w, r, &errors.Error{ + Code: errors.EInvalid, Msg: "Invalid post label map request", }) } @@ -106,7 +109,7 @@ func (h *LabelEmbeddedHandler) handlePostLabelMapping(w http.ResponseWriter, r * func (h *LabelEmbeddedHandler) handleFindResourceLabels(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - embeddedID, err := influxdb.IDFromString(chi.URLParam(r, "id")) + embeddedID, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { h.api.Err(w, r, err) return @@ -129,13 +132,13 @@ func (h *LabelEmbeddedHandler) handleFindResourceLabels(w http.ResponseWriter, r func (h *LabelEmbeddedHandler) handleDeleteLabelMapping(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - embeddedID, err := influxdb.IDFromString(chi.URLParam(r, "id")) + embeddedID, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { h.api.Err(w, r, err) return } - labelID, err := influxdb.IDFromString(chi.URLParam(r, "labelID")) + labelID, err := platform.IDFromString(chi.URLParam(r, "labelID")) if err != nil { h.api.Err(w, r, err) return diff --git a/label/http_server.go b/label/http_server.go index 3aa6902245d..a7c185001e2 100644 --- a/label/http_server.go +++ b/label/http_server.go @@ -5,6 +5,8 @@ import ( "fmt" "net/http" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/influxdata/influxdb/v2" @@ -108,7 +110,7 @@ func (h *LabelHandler) handlePostLabel(w http.ResponseWriter, r *http.Request) { // handleGetLabel is the HTTP handler for the GET /api/v2/labels/id route. func (h *LabelHandler) handleGetLabel(w http.ResponseWriter, r *http.Request) { - id, err := influxdb.IDFromString(chi.URLParam(r, "id")) + id, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { h.api.Err(w, r, err) return @@ -134,7 +136,7 @@ func (h *LabelHandler) handleGetLabels(w http.ResponseWriter, r *http.Request) { } if orgID := qp.Get("orgID"); orgID != "" { - i, err := influxdb.IDFromString(orgID) + i, err := platform.IDFromString(orgID) if err == nil { filter.OrgID = i } @@ -152,7 +154,7 @@ func (h *LabelHandler) handleGetLabels(w http.ResponseWriter, r *http.Request) { // handlePatchLabel is the HTTP handler for the PATCH /api/v2/labels route. func (h *LabelHandler) handlePatchLabel(w http.ResponseWriter, r *http.Request) { - id, err := influxdb.IDFromString(chi.URLParam(r, "id")) + id, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { h.api.Err(w, r, err) return @@ -177,7 +179,7 @@ func (h *LabelHandler) handlePatchLabel(w http.ResponseWriter, r *http.Request) // handleDeleteLabel is the HTTP handler for the DELETE /api/v2/labels/:id route. func (h *LabelHandler) handleDeleteLabel(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - id, err := influxdb.IDFromString(chi.URLParam(r, "id")) + id, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { h.api.Err(w, r, err) return diff --git a/label/http_server_test.go b/label/http_server_test.go index c38fc94a29b..34a4324abee 100644 --- a/label/http_server_test.go +++ b/label/http_server_test.go @@ -10,6 +10,9 @@ import ( "net/http/httptest" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" "github.com/google/go-cmp/cmp" influxdb "github.com/influxdata/influxdb/v2" @@ -130,7 +133,7 @@ func TestService_handleGetLabel(t *testing.T) { name: "get a label by id", fields: fields{ &mock.LabelService{ - FindLabelByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Label, error) { if id == influxdbtesting.MustIDBase16("020f755c3c082000") { return &influxdb.Label{ ID: influxdbtesting.MustIDBase16("020f755c3c082000"), @@ -171,9 +174,9 @@ func TestService_handleGetLabel(t *testing.T) { name: "not found", fields: fields{ &mock.LabelService{ - FindLabelByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + FindLabelByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Label, error) { + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrLabelNotFound, } }, @@ -367,7 +370,7 @@ func TestService_handlePatchLabel(t *testing.T) { name: "update label properties", fields: fields{ &mock.LabelService{ - UpdateLabelFn: func(ctx context.Context, id influxdb.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { + UpdateLabelFn: func(ctx context.Context, id platform.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { if id == influxdbtesting.MustIDBase16("020f755c3c082000") { l := &influxdb.Label{ ID: influxdbtesting.MustIDBase16("020f755c3c082000"), @@ -421,9 +424,9 @@ func TestService_handlePatchLabel(t *testing.T) { name: "label not found", fields: fields{ &mock.LabelService{ - UpdateLabelFn: func(ctx context.Context, id influxdb.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + UpdateLabelFn: func(ctx context.Context, id platform.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrLabelNotFound, } }, @@ -510,7 +513,7 @@ func TestService_handleDeleteLabel(t *testing.T) { name: "remove a label by id", fields: fields{ &mock.LabelService{ - DeleteLabelFn: func(ctx context.Context, id influxdb.ID) error { + DeleteLabelFn: func(ctx context.Context, id platform.ID) error { if id == influxdbtesting.MustIDBase16("020f755c3c082000") { return nil } @@ -530,9 +533,9 @@ func TestService_handleDeleteLabel(t *testing.T) { name: "label not found", fields: fields{ &mock.LabelService{ - DeleteLabelFn: func(ctx context.Context, id influxdb.ID) error { - return &influxdb.Error{ - Code: influxdb.ENotFound, + DeleteLabelFn: func(ctx context.Context, id platform.ID) error { + return &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrLabelNotFound, } }, diff --git a/label/middleware_auth.go b/label/middleware_auth.go index bbb68b3fedf..bc65b4afaab 100644 --- a/label/middleware_auth.go +++ b/label/middleware_auth.go @@ -3,6 +3,8 @@ package label import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/authorizer" ) @@ -40,7 +42,7 @@ func (s *AuthedLabelService) FindLabels(ctx context.Context, filter influxdb.Lab } // FindLabelByID checks to see if the authorizer on context has read access to the label id provided. -func (s *AuthedLabelService) FindLabelByID(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { +func (s *AuthedLabelService) FindLabelByID(ctx context.Context, id platform.ID) (*influxdb.Label, error) { l, err := s.s.FindLabelByID(ctx, id) if err != nil { return nil, err @@ -79,7 +81,7 @@ func (s *AuthedLabelService) FindResourceLabels(ctx context.Context, filter infl } // UpdateLabel checks to see if the authorizer on context has write access to the label provided. -func (s *AuthedLabelService) UpdateLabel(ctx context.Context, id influxdb.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { +func (s *AuthedLabelService) UpdateLabel(ctx context.Context, id platform.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { l, err := s.s.FindLabelByID(ctx, id) if err != nil { return nil, err @@ -91,7 +93,7 @@ func (s *AuthedLabelService) UpdateLabel(ctx context.Context, id influxdb.ID, up } // DeleteLabel checks to see if the authorizer on context has write access to the label provided. -func (s *AuthedLabelService) DeleteLabel(ctx context.Context, id influxdb.ID) error { +func (s *AuthedLabelService) DeleteLabel(ctx context.Context, id platform.ID) error { l, err := s.s.FindLabelByID(ctx, id) if err != nil { return err diff --git a/label/middleware_auth_test.go b/label/middleware_auth_test.go index b9f382067bd..f7f7d08134e 100644 --- a/label/middleware_auth_test.go +++ b/label/middleware_auth_test.go @@ -6,6 +6,9 @@ import ( "sort" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" influxdbcontext "github.com/influxdata/influxdb/v2/context" @@ -20,7 +23,7 @@ const ( var ( orgOneInfluxID = influxdbtesting.MustIDBase16(orgOneID) orgSvc = &mock.OrganizationService{ - FindResourceOrganizationIDF: func(_ context.Context, _ influxdb.ResourceType, _ influxdb.ID) (influxdb.ID, error) { + FindResourceOrganizationIDF: func(_ context.Context, _ influxdb.ResourceType, _ platform.ID) (platform.ID, error) { return orgOneInfluxID, nil }, } @@ -45,7 +48,7 @@ func TestLabelService_FindLabelByID(t *testing.T) { } type args struct { permission influxdb.Permission - id influxdb.ID + id platform.ID } type wants struct { err error @@ -61,7 +64,7 @@ func TestLabelService_FindLabelByID(t *testing.T) { name: "authorized to access id", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: id, OrgID: orgOneInfluxID, @@ -87,7 +90,7 @@ func TestLabelService_FindLabelByID(t *testing.T) { name: "unauthorized to access id", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: id, OrgID: orgOneInfluxID, @@ -106,9 +109,9 @@ func TestLabelService_FindLabelByID(t *testing.T) { id: 1, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/020f755c3c083000/labels/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -291,7 +294,7 @@ func TestLabelService_UpdateLabel(t *testing.T) { LabelService influxdb.LabelService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -308,13 +311,13 @@ func TestLabelService_UpdateLabel(t *testing.T) { name: "authorized to update label", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, }, nil }, - UpdateLabelFn: func(ctx context.Context, id influxdb.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { + UpdateLabelFn: func(ctx context.Context, id platform.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, @@ -342,13 +345,13 @@ func TestLabelService_UpdateLabel(t *testing.T) { name: "unauthorized to update label", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, }, nil }, - UpdateLabelFn: func(ctx context.Context, id influxdb.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { + UpdateLabelFn: func(ctx context.Context, id platform.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, @@ -369,9 +372,9 @@ func TestLabelService_UpdateLabel(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/020f755c3c083000/labels/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -395,7 +398,7 @@ func TestLabelService_DeleteLabel(t *testing.T) { LabelService influxdb.LabelService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -412,13 +415,13 @@ func TestLabelService_DeleteLabel(t *testing.T) { name: "authorized to delete label", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, }, nil }, - DeleteLabelFn: func(ctx context.Context, id influxdb.ID) error { + DeleteLabelFn: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -444,13 +447,13 @@ func TestLabelService_DeleteLabel(t *testing.T) { name: "unauthorized to delete label", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, }, nil }, - DeleteLabelFn: func(ctx context.Context, id influxdb.ID) error { + DeleteLabelFn: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -469,9 +472,9 @@ func TestLabelService_DeleteLabel(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/020f755c3c083000/labels/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -526,9 +529,9 @@ func TestLabelService_CreateLabel(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/020f755c3c083000/labels is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -550,9 +553,9 @@ func TestLabelService_CreateLabel(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/020f755c3c083000/labels is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -805,9 +808,9 @@ func TestLabelService_FindResourceLabels(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/020f755c3c083000/buckets/000000000000000a is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -852,7 +855,7 @@ func TestLabelService_CreateLabelMapping(t *testing.T) { name: "authorized to create label mapping", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, @@ -893,7 +896,7 @@ func TestLabelService_CreateLabelMapping(t *testing.T) { name: "unauthorized to create label mapping for resources on which the user does not have write access", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, @@ -920,8 +923,8 @@ func TestLabelService_CreateLabelMapping(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EUnauthorized, + err: &errors.Error{ + Code: errors.EUnauthorized, Msg: "write:orgs/020f755c3c083000/buckets/0000000000000002 is unauthorized", }, }, @@ -930,7 +933,7 @@ func TestLabelService_CreateLabelMapping(t *testing.T) { name: "unauthorized to create label mapping", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, @@ -957,9 +960,9 @@ func TestLabelService_CreateLabelMapping(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/020f755c3c083000/labels/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -1000,7 +1003,7 @@ func TestLabelService_DeleteLabelMapping(t *testing.T) { name: "authorized to delete label mapping", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, @@ -1041,7 +1044,7 @@ func TestLabelService_DeleteLabelMapping(t *testing.T) { name: "unauthorized to delete label mapping containing a resources on which the user does not have write access", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, @@ -1068,8 +1071,8 @@ func TestLabelService_DeleteLabelMapping(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EUnauthorized, + err: &errors.Error{ + Code: errors.EUnauthorized, Msg: "write:orgs/020f755c3c083000/buckets/0000000000000002 is unauthorized", }, }, @@ -1078,7 +1081,7 @@ func TestLabelService_DeleteLabelMapping(t *testing.T) { name: "unauthorized to delete label mapping", fields: fields{ LabelService: &mock.LabelService{ - FindLabelByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Label, error) { + FindLabelByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: 1, OrgID: orgOneInfluxID, @@ -1105,9 +1108,9 @@ func TestLabelService_DeleteLabelMapping(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/020f755c3c083000/labels/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, diff --git a/label/middleware_logging.go b/label/middleware_logging.go index af5156423c8..1e97e917cf7 100644 --- a/label/middleware_logging.go +++ b/label/middleware_logging.go @@ -5,6 +5,8 @@ import ( "fmt" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "go.uber.org/zap" ) @@ -35,7 +37,7 @@ func (l *LabelLogger) CreateLabel(ctx context.Context, label *influxdb.Label) (e return l.labelService.CreateLabel(ctx, label) } -func (l *LabelLogger) FindLabelByID(ctx context.Context, id influxdb.ID) (label *influxdb.Label, err error) { +func (l *LabelLogger) FindLabelByID(ctx context.Context, id platform.ID) (label *influxdb.Label, err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -74,7 +76,7 @@ func (l *LabelLogger) FindResourceLabels(ctx context.Context, filter influxdb.La return l.labelService.FindResourceLabels(ctx, filter) } -func (l *LabelLogger) UpdateLabel(ctx context.Context, id influxdb.ID, upd influxdb.LabelUpdate) (lbl *influxdb.Label, err error) { +func (l *LabelLogger) UpdateLabel(ctx context.Context, id platform.ID, upd influxdb.LabelUpdate) (lbl *influxdb.Label, err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -87,7 +89,7 @@ func (l *LabelLogger) UpdateLabel(ctx context.Context, id influxdb.ID, upd influ return l.labelService.UpdateLabel(ctx, id, upd) } -func (l *LabelLogger) DeleteLabel(ctx context.Context, id influxdb.ID) (err error) { +func (l *LabelLogger) DeleteLabel(ctx context.Context, id platform.ID) (err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { diff --git a/label/middleware_metrics.go b/label/middleware_metrics.go index 9a84cac65a8..d6a60848c98 100644 --- a/label/middleware_metrics.go +++ b/label/middleware_metrics.go @@ -3,6 +3,8 @@ package label import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/metric" "github.com/prometheus/client_golang/prometheus" @@ -31,7 +33,7 @@ func (m *LabelMetrics) CreateLabel(ctx context.Context, l *influxdb.Label) (err return rec(err) } -func (m *LabelMetrics) FindLabelByID(ctx context.Context, id influxdb.ID) (label *influxdb.Label, err error) { +func (m *LabelMetrics) FindLabelByID(ctx context.Context, id platform.ID) (label *influxdb.Label, err error) { rec := m.rec.Record("find_label_by_id") l, err := m.labelService.FindLabelByID(ctx, id) return l, rec(err) @@ -49,13 +51,13 @@ func (m *LabelMetrics) FindResourceLabels(ctx context.Context, filter influxdb.L return l, rec(err) } -func (m *LabelMetrics) UpdateLabel(ctx context.Context, id influxdb.ID, upd influxdb.LabelUpdate) (lbl *influxdb.Label, err error) { +func (m *LabelMetrics) UpdateLabel(ctx context.Context, id platform.ID, upd influxdb.LabelUpdate) (lbl *influxdb.Label, err error) { rec := m.rec.Record("update_label") l, err := m.labelService.UpdateLabel(ctx, id, upd) return l, rec(err) } -func (m *LabelMetrics) DeleteLabel(ctx context.Context, id influxdb.ID) (err error) { +func (m *LabelMetrics) DeleteLabel(ctx context.Context, id platform.ID) (err error) { rec := m.rec.Record("delete_label") err = m.labelService.DeleteLabel(ctx, id) return rec(err) diff --git a/label/service.go b/label/service.go index 318dad322e6..e470de2e7c2 100644 --- a/label/service.go +++ b/label/service.go @@ -4,6 +4,9 @@ import ( "context" "strings" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" ) @@ -21,8 +24,8 @@ func NewService(st *Store) influxdb.LabelService { // CreateLabel creates a new label. func (s *Service) CreateLabel(ctx context.Context, l *influxdb.Label) error { if err := l.Validate(); err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -49,7 +52,7 @@ func (s *Service) CreateLabel(ctx context.Context, l *influxdb.Label) error { } // FindLabelByID finds a label by its ID -func (s *Service) FindLabelByID(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { +func (s *Service) FindLabelByID(ctx context.Context, id platform.ID) (*influxdb.Label, error) { var l *influxdb.Label err := s.store.View(ctx, func(tx kv.Tx) error { @@ -62,7 +65,7 @@ func (s *Service) FindLabelByID(ctx context.Context, id influxdb.ID) (*influxdb. }) if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -101,12 +104,12 @@ func (s *Service) FindResourceLabels(ctx context.Context, filter influxdb.LabelM } // UpdateLabel updates a label. -func (s *Service) UpdateLabel(ctx context.Context, id influxdb.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { +func (s *Service) UpdateLabel(ctx context.Context, id platform.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { var label *influxdb.Label err := s.store.Update(ctx, func(tx kv.Tx) error { l, e := s.store.UpdateLabel(ctx, tx, id, upd) if e != nil { - return &influxdb.Error{ + return &errors.Error{ Err: e, } } @@ -118,12 +121,12 @@ func (s *Service) UpdateLabel(ctx context.Context, id influxdb.ID, upd influxdb. } // DeleteLabel deletes a label. -func (s *Service) DeleteLabel(ctx context.Context, id influxdb.ID) error { +func (s *Service) DeleteLabel(ctx context.Context, id platform.ID) error { err := s.store.Update(ctx, func(tx kv.Tx) error { return s.store.DeleteLabel(ctx, tx, id) }) if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -167,7 +170,7 @@ func (s *Service) DeleteLabelMapping(ctx context.Context, m *influxdb.LabelMappi return s.store.DeleteLabelMapping(ctx, tx, m) }) if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } diff --git a/label/storage.go b/label/storage.go index ec1e607f11c..07ff8e8291b 100644 --- a/label/storage.go +++ b/label/storage.go @@ -3,7 +3,9 @@ package label import ( "context" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2/kit/tracing" "github.com/influxdata/influxdb/v2/kv" "github.com/influxdata/influxdb/v2/snowflake" @@ -20,7 +22,7 @@ var ( type Store struct { kvStore kv.Store - IDGenerator influxdb.IDGenerator + IDGenerator platform.IDGenerator } func NewStore(kvStore kv.Store) (*Store, error) { @@ -62,7 +64,7 @@ func (s *Store) setup() error { // generateSafeID attempts to create ids for buckets // and orgs that are without backslash, commas, and spaces, BUT ALSO do not already exist. -func (s *Store) generateSafeID(ctx context.Context, tx kv.Tx, bucket []byte) (influxdb.ID, error) { +func (s *Store) generateSafeID(ctx context.Context, tx kv.Tx, bucket []byte) (platform.ID, error) { for i := 0; i < MaxIDGenerationN; i++ { id := s.IDGenerator.ID() @@ -75,19 +77,19 @@ func (s *Store) generateSafeID(ctx context.Context, tx kv.Tx, bucket []byte) (in continue } - return influxdb.InvalidID(), err + return platform.InvalidID(), err } - return influxdb.InvalidID(), ErrFailureGeneratingID + return platform.InvalidID(), ErrFailureGeneratingID } -func (s *Store) uniqueID(ctx context.Context, tx kv.Tx, bucket []byte, id influxdb.ID) error { +func (s *Store) uniqueID(ctx context.Context, tx kv.Tx, bucket []byte, id platform.ID) error { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() encodedID, err := id.Encode() if err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Err: err, } } diff --git a/label/storage_label.go b/label/storage_label.go index 8a0079db48a..b88cc269b59 100644 --- a/label/storage_label.go +++ b/label/storage_label.go @@ -6,6 +6,9 @@ import ( "fmt" "strings" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" ) @@ -20,47 +23,47 @@ func (s *Store) CreateLabel(ctx context.Context, tx kv.Tx, l *influxdb.Label) er v, err := json.Marshal(l) if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } encodedID, err := l.ID.Encode() if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } idx, err := tx.Bucket(labelIndex) if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } key, err := labelIndexKey(l) if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } if err := idx.Put([]byte(key), encodedID); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } b, err := tx.Bucket(labelBucket) if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } if err := b.Put(encodedID, v); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -85,10 +88,10 @@ func (s *Store) ListLabels(ctx context.Context, tx kv.Tx, filter influxdb.LabelF return ls, nil } -func (s *Store) GetLabel(ctx context.Context, tx kv.Tx, id influxdb.ID) (*influxdb.Label, error) { +func (s *Store) GetLabel(ctx context.Context, tx kv.Tx, id platform.ID) (*influxdb.Label, error) { encodedID, err := id.Encode() if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -100,8 +103,8 @@ func (s *Store) GetLabel(ctx context.Context, tx kv.Tx, id influxdb.ID) (*influx v, err := b.Get(encodedID) if kv.IsNotFound(err) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrLabelNotFound, } } @@ -112,7 +115,7 @@ func (s *Store) GetLabel(ctx context.Context, tx kv.Tx, id influxdb.ID) (*influx var l influxdb.Label if err := json.Unmarshal(v, &l); err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -120,7 +123,7 @@ func (s *Store) GetLabel(ctx context.Context, tx kv.Tx, id influxdb.ID) (*influx return &l, nil } -func (s *Store) UpdateLabel(ctx context.Context, tx kv.Tx, id influxdb.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { +func (s *Store) UpdateLabel(ctx context.Context, tx kv.Tx, id platform.ID, upd influxdb.LabelUpdate) (*influxdb.Label, error) { label, err := s.GetLabel(ctx, tx, id) if err != nil { return nil, err @@ -143,69 +146,69 @@ func (s *Store) UpdateLabel(ctx context.Context, tx kv.Tx, id influxdb.ID, upd i idx, err := tx.Bucket(labelIndex) if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } key, err := labelIndexKey(label) if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } if err := idx.Delete(key); err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } label.Name = upd.Name if err := uniqueLabelName(ctx, tx, label); err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } } if err := label.Validate(); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } v, err := json.Marshal(label) if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } encodedID, err := label.ID.Encode() if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } idx, err := tx.Bucket(labelIndex) if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } key, err := labelIndexKey(label) if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } if err := idx.Put([]byte(key), encodedID); err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -216,7 +219,7 @@ func (s *Store) UpdateLabel(ctx context.Context, tx kv.Tx, id influxdb.ID, upd i } if err := b.Put(encodedID, v); err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -224,14 +227,14 @@ func (s *Store) UpdateLabel(ctx context.Context, tx kv.Tx, id influxdb.ID, upd i return label, nil } -func (s *Store) DeleteLabel(ctx context.Context, tx kv.Tx, id influxdb.ID) error { +func (s *Store) DeleteLabel(ctx context.Context, tx kv.Tx, id platform.ID) error { label, err := s.GetLabel(ctx, tx, id) if err != nil { return ErrLabelNotFound } encodedID, idErr := id.Encode() if idErr != nil { - return &influxdb.Error{ + return &errors.Error{ Err: idErr, } } @@ -242,27 +245,27 @@ func (s *Store) DeleteLabel(ctx context.Context, tx kv.Tx, id influxdb.ID) error } if err := b.Delete(encodedID); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } idx, err := tx.Bucket(labelIndex) if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } key, err := labelIndexKey(label) if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } if err := idx.Delete(key); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -275,14 +278,14 @@ func (s *Store) DeleteLabel(ctx context.Context, tx kv.Tx, id influxdb.ID) error func (s *Store) CreateLabelMapping(ctx context.Context, tx kv.Tx, m *influxdb.LabelMapping) error { v, err := json.Marshal(m) if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } key, err := labelMappingKey(m) if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -293,7 +296,7 @@ func (s *Store) CreateLabelMapping(ctx context.Context, tx kv.Tx, m *influxdb.La } if err := idx.Put(key, v); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -303,7 +306,7 @@ func (s *Store) CreateLabelMapping(ctx context.Context, tx kv.Tx, m *influxdb.La func (s *Store) FindResourceLabels(ctx context.Context, tx kv.Tx, filter influxdb.LabelMappingFilter, ls *[]*influxdb.Label) error { if !filter.ResourceID.Valid() { - return &influxdb.Error{Code: influxdb.EInvalid, Msg: "filter requires a valid resource id", Err: influxdb.ErrInvalidID} + return &errors.Error{Code: errors.EInvalid, Msg: "filter requires a valid resource id", Err: platform.ErrInvalidID} } idx, err := tx.Bucket(labelMappingBucket) if err != nil { @@ -346,7 +349,7 @@ func (s *Store) FindResourceLabels(ctx context.Context, tx kv.Tx, filter influxd func (s *Store) DeleteLabelMapping(ctx context.Context, tx kv.Tx, m *influxdb.LabelMapping) error { key, err := labelMappingKey(m) if err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -357,7 +360,7 @@ func (s *Store) DeleteLabelMapping(ctx context.Context, tx kv.Tx, m *influxdb.La } if err := idx.Delete(key); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -370,21 +373,21 @@ func (s *Store) DeleteLabelMapping(ctx context.Context, tx kv.Tx, m *influxdb.La func labelMappingKey(m *influxdb.LabelMapping) ([]byte, error) { lid, err := m.LabelID.Encode() if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } rid, err := m.ResourceID.Encode() if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } - key := make([]byte, influxdb.IDLength+influxdb.IDLength) // len(rid) + len(lid) + key := make([]byte, platform.IDLength+platform.IDLength) // len(rid) + len(lid) copy(key, rid) copy(key[len(rid):], lid) @@ -394,8 +397,8 @@ func labelMappingKey(m *influxdb.LabelMapping) ([]byte, error) { // labelAlreadyExistsError is used when creating a new label with // a name that has already been used. Label names must be unique. func labelAlreadyExistsError(lbl *influxdb.Label) error { - return &influxdb.Error{ - Code: influxdb.EConflict, + return &errors.Error{ + Code: errors.EConflict, Msg: fmt.Sprintf("label with name %s already exists", lbl.Name), } } @@ -403,15 +406,15 @@ func labelAlreadyExistsError(lbl *influxdb.Label) error { func labelIndexKey(l *influxdb.Label) ([]byte, error) { orgID, err := l.OrgID.Encode() if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } - k := make([]byte, influxdb.IDLength+len(l.Name)) + k := make([]byte, platform.IDLength+len(l.Name)) copy(k, orgID) - copy(k[influxdb.IDLength:], []byte(strings.ToLower((l.Name)))) + copy(k[platform.IDLength:], []byte(strings.ToLower((l.Name)))) return k, nil } @@ -422,17 +425,17 @@ func filterLabelsFn(filter influxdb.LabelFilter) func(l *influxdb.Label) bool { } } -func decodeLabelMappingKey(key []byte) (resourceID influxdb.ID, labelID influxdb.ID, err error) { - if len(key) != 2*influxdb.IDLength { - return 0, 0, &influxdb.Error{Code: influxdb.EInvalid, Msg: "malformed label mapping key (please report this error)"} +func decodeLabelMappingKey(key []byte) (resourceID platform.ID, labelID platform.ID, err error) { + if len(key) != 2*platform.IDLength { + return 0, 0, &errors.Error{Code: errors.EInvalid, Msg: "malformed label mapping key (please report this error)"} } - if err := (&resourceID).Decode(key[:influxdb.IDLength]); err != nil { - return 0, 0, &influxdb.Error{Code: influxdb.EInvalid, Msg: "bad resource id", Err: influxdb.ErrInvalidID} + if err := (&resourceID).Decode(key[:platform.IDLength]); err != nil { + return 0, 0, &errors.Error{Code: errors.EInvalid, Msg: "bad resource id", Err: platform.ErrInvalidID} } - if err := (&labelID).Decode(key[influxdb.IDLength:]); err != nil { - return 0, 0, &influxdb.Error{Code: influxdb.EInvalid, Msg: "bad label id", Err: influxdb.ErrInvalidID} + if err := (&labelID).Decode(key[platform.IDLength:]); err != nil { + return 0, 0, &errors.Error{Code: errors.EInvalid, Msg: "bad label id", Err: platform.ErrInvalidID} } return resourceID, labelID, nil diff --git a/label/storage_test.go b/label/storage_test.go index 042b89fc43f..fe3ea8fdc0d 100644 --- a/label/storage_test.go +++ b/label/storage_test.go @@ -3,6 +3,7 @@ package label_test import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" "reflect" "testing" @@ -18,10 +19,10 @@ import ( func TestLabels(t *testing.T) { setup := func(t *testing.T, store *label.Store, tx kv.Tx) { for i := 1; i <= 10; i++ { - mock.SetIDForFunc(&store.IDGenerator, influxdb.ID(i), func() { + mock.SetIDForFunc(&store.IDGenerator, platform.ID(i), func() { err := store.CreateLabel(context.Background(), tx, &influxdb.Label{ Name: fmt.Sprintf("labelname%d", i), - OrgID: influxdb.ID(i), + OrgID: platform.ID(i), }) if err != nil { @@ -34,10 +35,10 @@ func TestLabels(t *testing.T) { setupForList := func(t *testing.T, store *label.Store, tx kv.Tx) { setup(t, store, tx) - mock.SetIDForFunc(&store.IDGenerator, influxdb.ID(11), func() { + mock.SetIDForFunc(&store.IDGenerator, platform.ID(11), func() { err := store.CreateLabel(context.Background(), tx, &influxdb.Label{ Name: fmt.Sprintf("labelname%d", 11), - OrgID: influxdb.ID(5), + OrgID: platform.ID(5), }) if err != nil { t.Fatal(err) @@ -67,9 +68,9 @@ func TestLabels(t *testing.T) { expected := []*influxdb.Label{} for i := 1; i <= 10; i++ { expected = append(expected, &influxdb.Label{ - ID: influxdb.ID(i), + ID: platform.ID(i), Name: fmt.Sprintf("labelname%d", i), - OrgID: influxdb.ID(i), + OrgID: platform.ID(i), }) } if !reflect.DeepEqual(labels, expected) { @@ -81,15 +82,15 @@ func TestLabels(t *testing.T) { name: "get", setup: setup, results: func(t *testing.T, store *label.Store, tx kv.Tx) { - label, err := store.GetLabel(context.Background(), tx, influxdb.ID(1)) + label, err := store.GetLabel(context.Background(), tx, platform.ID(1)) if err != nil { t.Fatal(err) } expected := &influxdb.Label{ - ID: influxdb.ID(1), + ID: platform.ID(1), Name: "labelname1", - OrgID: influxdb.ID(1), + OrgID: platform.ID(1), } if !reflect.DeepEqual(label, expected) { @@ -114,15 +115,15 @@ func TestLabels(t *testing.T) { expected := []*influxdb.Label{} for i := 1; i <= 10; i++ { expected = append(expected, &influxdb.Label{ - ID: influxdb.ID(i), + ID: platform.ID(i), Name: fmt.Sprintf("labelname%d", i), - OrgID: influxdb.ID(i), + OrgID: platform.ID(i), }) } expected = append(expected, &influxdb.Label{ - ID: influxdb.ID(11), + ID: platform.ID(11), Name: fmt.Sprintf("labelname%d", 11), - OrgID: influxdb.ID(5), + OrgID: platform.ID(5), }) if !reflect.DeepEqual(labels, expected) { @@ -140,16 +141,16 @@ func TestLabels(t *testing.T) { } expectedLabel := []*influxdb.Label{&influxdb.Label{ - ID: influxdb.ID(5), + ID: platform.ID(5), Name: "labelname5", - OrgID: influxdb.ID(5), + OrgID: platform.ID(5), }} if !reflect.DeepEqual(l, expectedLabel) { t.Fatalf("label returned by list did not match expected: \n%+v\n%+v", l, expectedLabel) } // filter by org id - id := influxdb.ID(5) + id := platform.ID(5) l, err = store.ListLabels(context.Background(), tx, influxdb.LabelFilter{OrgID: &id}) if err != nil { t.Fatal(err) @@ -161,13 +162,13 @@ func TestLabels(t *testing.T) { expectedLabel = []*influxdb.Label{ &influxdb.Label{ - ID: influxdb.ID(5), + ID: platform.ID(5), Name: "labelname5", - OrgID: influxdb.ID(5)}, + OrgID: platform.ID(5)}, { - ID: influxdb.ID(11), + ID: platform.ID(11), Name: "labelname11", - OrgID: influxdb.ID(5), + OrgID: platform.ID(5), }} if !reflect.DeepEqual(l, expectedLabel) { t.Fatalf("label returned by list did not match expected: \n%+v\n%+v", l, expectedLabel) @@ -179,7 +180,7 @@ func TestLabels(t *testing.T) { setup: setup, update: func(t *testing.T, store *label.Store, tx kv.Tx) { upd := influxdb.LabelUpdate{Name: "newName"} - updated, err := store.UpdateLabel(context.Background(), tx, influxdb.ID(1), upd) + updated, err := store.UpdateLabel(context.Background(), tx, platform.ID(1), upd) if err != nil { t.Fatal(err) } @@ -189,7 +190,7 @@ func TestLabels(t *testing.T) { } }, results: func(t *testing.T, store *label.Store, tx kv.Tx) { - la, err := store.GetLabel(context.Background(), tx, influxdb.ID(1)) + la, err := store.GetLabel(context.Background(), tx, platform.ID(1)) if err != nil { t.Fatal(err) } @@ -203,12 +204,12 @@ func TestLabels(t *testing.T) { name: "delete", setup: setup, update: func(t *testing.T, store *label.Store, tx kv.Tx) { - err := store.DeleteLabel(context.Background(), tx, influxdb.ID(5)) + err := store.DeleteLabel(context.Background(), tx, platform.ID(5)) if err != nil { t.Fatal(err) } - err = store.DeleteLabel(context.Background(), tx, influxdb.ID(5)) + err = store.DeleteLabel(context.Background(), tx, platform.ID(5)) if err != label.ErrLabelNotFound { t.Fatal("expected label not found error when deleting bucket that has already been deleted, got: ", err) } diff --git a/label_test.go b/label_test.go index 9a38b5b6842..e3868f0b095 100644 --- a/label_test.go +++ b/label_test.go @@ -1,6 +1,7 @@ package influxdb_test import ( + "github.com/influxdata/influxdb/v2/kit/platform" "testing" "github.com/influxdata/influxdb/v2" @@ -14,7 +15,7 @@ const ( func TestLabelValidate(t *testing.T) { type fields struct { Name string - OrgID influxdb.ID + OrgID platform.ID } tests := []struct { name string diff --git a/lookup.go b/lookup.go index d392ef675cd..082c7da9330 100644 --- a/lookup.go +++ b/lookup.go @@ -2,10 +2,12 @@ package influxdb import ( "context" + + "github.com/influxdata/influxdb/v2/kit/platform" ) // LookupService provides field lookup for the resource and ID. type LookupService interface { // FindResourceName returns the name for the resource and ID. - FindResourceName(ctx context.Context, resource ResourceType, id ID) (string, error) + FindResourceName(ctx context.Context, resource ResourceType, id platform.ID) (string, error) } diff --git a/mock/auth_service.go b/mock/auth_service.go index 25eeb1afb56..280ef158bbb 100644 --- a/mock/auth_service.go +++ b/mock/auth_service.go @@ -3,6 +3,8 @@ package mock import ( "context" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" ) @@ -14,33 +16,33 @@ type AuthorizationService struct { CloseFn func() error // Methods for an platform.AuthorizationService - FindAuthorizationByIDFn func(context.Context, platform.ID) (*platform.Authorization, error) + FindAuthorizationByIDFn func(context.Context, platform2.ID) (*platform.Authorization, error) FindAuthorizationByTokenFn func(context.Context, string) (*platform.Authorization, error) FindAuthorizationsFn func(context.Context, platform.AuthorizationFilter, ...platform.FindOptions) ([]*platform.Authorization, int, error) CreateAuthorizationFn func(context.Context, *platform.Authorization) error - DeleteAuthorizationFn func(context.Context, platform.ID) error - UpdateAuthorizationFn func(context.Context, platform.ID, *platform.AuthorizationUpdate) (*platform.Authorization, error) + DeleteAuthorizationFn func(context.Context, platform2.ID) error + UpdateAuthorizationFn func(context.Context, platform2.ID, *platform.AuthorizationUpdate) (*platform.Authorization, error) } // NewAuthorizationService returns a mock AuthorizationService where its methods will return // zero values. func NewAuthorizationService() *AuthorizationService { return &AuthorizationService{ - FindAuthorizationByIDFn: func(context.Context, platform.ID) (*platform.Authorization, error) { return nil, nil }, + FindAuthorizationByIDFn: func(context.Context, platform2.ID) (*platform.Authorization, error) { return nil, nil }, FindAuthorizationByTokenFn: func(context.Context, string) (*platform.Authorization, error) { return nil, nil }, FindAuthorizationsFn: func(context.Context, platform.AuthorizationFilter, ...platform.FindOptions) ([]*platform.Authorization, int, error) { return nil, 0, nil }, CreateAuthorizationFn: func(context.Context, *platform.Authorization) error { return nil }, - DeleteAuthorizationFn: func(context.Context, platform.ID) error { return nil }, - UpdateAuthorizationFn: func(context.Context, platform.ID, *platform.AuthorizationUpdate) (*platform.Authorization, error) { + DeleteAuthorizationFn: func(context.Context, platform2.ID) error { return nil }, + UpdateAuthorizationFn: func(context.Context, platform2.ID, *platform.AuthorizationUpdate) (*platform.Authorization, error) { return nil, nil }, } } // FindAuthorizationByID returns a single authorization by ID. -func (s *AuthorizationService) FindAuthorizationByID(ctx context.Context, id platform.ID) (*platform.Authorization, error) { +func (s *AuthorizationService) FindAuthorizationByID(ctx context.Context, id platform2.ID) (*platform.Authorization, error) { return s.FindAuthorizationByIDFn(ctx, id) } @@ -59,11 +61,11 @@ func (s *AuthorizationService) CreateAuthorization(ctx context.Context, authoriz } // DeleteAuthorization removes a authorization by ID. -func (s *AuthorizationService) DeleteAuthorization(ctx context.Context, id platform.ID) error { +func (s *AuthorizationService) DeleteAuthorization(ctx context.Context, id platform2.ID) error { return s.DeleteAuthorizationFn(ctx, id) } // UpdateAuthorization updates the status and description if available. -func (s *AuthorizationService) UpdateAuthorization(ctx context.Context, id platform.ID, upd *platform.AuthorizationUpdate) (*platform.Authorization, error) { +func (s *AuthorizationService) UpdateAuthorization(ctx context.Context, id platform2.ID, upd *platform.AuthorizationUpdate) (*platform.Authorization, error) { return s.UpdateAuthorizationFn(ctx, id, upd) } diff --git a/mock/authorization.go b/mock/authorization.go index 556ae1f7f80..9c0653a5371 100644 --- a/mock/authorization.go +++ b/mock/authorization.go @@ -2,6 +2,7 @@ package mock import ( influxdb "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" ) // ensure Authorizer implements influxdb.Authorizer @@ -11,7 +12,7 @@ var _ influxdb.Authorizer = (*Authorizer)(nil) type Authorizer struct { Permissions []influxdb.Permission AllowAll bool - UserID influxdb.ID + UserID platform.ID } func NewMockAuthorizer(allowAll bool, permissions []influxdb.Permission) *Authorizer { @@ -34,11 +35,11 @@ func (a *Authorizer) PermissionSet() (influxdb.PermissionSet, error) { return a.Permissions, nil } -func (a *Authorizer) Identifier() influxdb.ID { +func (a *Authorizer) Identifier() platform.ID { return 1 } -func (a *Authorizer) GetUserID() influxdb.ID { +func (a *Authorizer) GetUserID() platform.ID { if a.UserID.Valid() { return a.UserID } diff --git a/mock/bucket_service.go b/mock/bucket_service.go index f2b080237cb..72339898fd1 100644 --- a/mock/bucket_service.go +++ b/mock/bucket_service.go @@ -4,6 +4,8 @@ import ( "context" "time" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" ) @@ -15,9 +17,9 @@ type BucketService struct { CloseFn func() error // Methods for an platform.BucketService - FindBucketByIDFn func(context.Context, platform.ID) (*platform.Bucket, error) + FindBucketByIDFn func(context.Context, platform2.ID) (*platform.Bucket, error) FindBucketByIDCalls SafeCount - FindBucketByNameFn func(context.Context, platform.ID, string) (*platform.Bucket, error) + FindBucketByNameFn func(context.Context, platform2.ID, string) (*platform.Bucket, error) FindBucketByNameCalls SafeCount FindBucketFn func(context.Context, platform.BucketFilter) (*platform.Bucket, error) FindBucketCalls SafeCount @@ -25,9 +27,9 @@ type BucketService struct { FindBucketsCalls SafeCount CreateBucketFn func(context.Context, *platform.Bucket) error CreateBucketCalls SafeCount - UpdateBucketFn func(context.Context, platform.ID, platform.BucketUpdate) (*platform.Bucket, error) + UpdateBucketFn func(context.Context, platform2.ID, platform.BucketUpdate) (*platform.Bucket, error) UpdateBucketCalls SafeCount - DeleteBucketFn func(context.Context, platform.ID) error + DeleteBucketFn func(context.Context, platform2.ID) error DeleteBucketCalls SafeCount } @@ -37,10 +39,10 @@ func NewBucketService() *BucketService { return &BucketService{ OpenFn: func() error { return nil }, CloseFn: func() error { return nil }, - FindBucketByIDFn: func(context.Context, platform.ID) (*platform.Bucket, error) { return nil, nil }, - FindBucketByNameFn: func(context.Context, platform.ID, string) (*platform.Bucket, error) { + FindBucketByIDFn: func(context.Context, platform2.ID) (*platform.Bucket, error) { return nil, nil }, + FindBucketByNameFn: func(context.Context, platform2.ID, string) (*platform.Bucket, error) { return &platform.Bucket{ - ID: platform.ID(10), + ID: platform2.ID(10), Type: platform.BucketTypeSystem, Name: "_tasks", RetentionPeriod: time.Hour * 24 * 3, @@ -52,8 +54,8 @@ func NewBucketService() *BucketService { return nil, 0, nil }, CreateBucketFn: func(context.Context, *platform.Bucket) error { return nil }, - UpdateBucketFn: func(context.Context, platform.ID, platform.BucketUpdate) (*platform.Bucket, error) { return nil, nil }, - DeleteBucketFn: func(context.Context, platform.ID) error { return nil }, + UpdateBucketFn: func(context.Context, platform2.ID, platform.BucketUpdate) (*platform.Bucket, error) { return nil, nil }, + DeleteBucketFn: func(context.Context, platform2.ID) error { return nil }, } } @@ -64,13 +66,13 @@ func (s *BucketService) Open() error { return s.OpenFn() } func (s *BucketService) Close() error { return s.CloseFn() } // FindBucketByID returns a single bucket by ID. -func (s *BucketService) FindBucketByID(ctx context.Context, id platform.ID) (*platform.Bucket, error) { +func (s *BucketService) FindBucketByID(ctx context.Context, id platform2.ID) (*platform.Bucket, error) { defer s.FindBucketByIDCalls.IncrFn()() return s.FindBucketByIDFn(ctx, id) } // FindBucketByName returns a single bucket by name. -func (s *BucketService) FindBucketByName(ctx context.Context, orgID platform.ID, name string) (*platform.Bucket, error) { +func (s *BucketService) FindBucketByName(ctx context.Context, orgID platform2.ID, name string) (*platform.Bucket, error) { defer s.FindBucketByNameCalls.IncrFn()() return s.FindBucketByNameFn(ctx, orgID, name) } @@ -94,13 +96,13 @@ func (s *BucketService) CreateBucket(ctx context.Context, bucket *platform.Bucke } // UpdateBucket updates a single bucket with changeset. -func (s *BucketService) UpdateBucket(ctx context.Context, id platform.ID, upd platform.BucketUpdate) (*platform.Bucket, error) { +func (s *BucketService) UpdateBucket(ctx context.Context, id platform2.ID, upd platform.BucketUpdate) (*platform.Bucket, error) { defer s.UpdateBucketCalls.IncrFn()() return s.UpdateBucketFn(ctx, id, upd) } // DeleteBucket removes a bucket by ID. -func (s *BucketService) DeleteBucket(ctx context.Context, id platform.ID) error { +func (s *BucketService) DeleteBucket(ctx context.Context, id platform2.ID) error { defer s.DeleteBucketCalls.IncrFn()() return s.DeleteBucketFn(ctx, id) } diff --git a/mock/check_service.go b/mock/check_service.go index 6d33d3bb187..2c770c3c738 100644 --- a/mock/check_service.go +++ b/mock/check_service.go @@ -3,6 +3,8 @@ package mock import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -13,19 +15,19 @@ type CheckService struct { UserResourceMappingService // Methods for an influxdb.CheckService - FindCheckByIDFn func(context.Context, influxdb.ID) (influxdb.Check, error) + FindCheckByIDFn func(context.Context, platform.ID) (influxdb.Check, error) FindCheckByIDCalls SafeCount FindCheckFn func(context.Context, influxdb.CheckFilter) (influxdb.Check, error) FindCheckCalls SafeCount FindChecksFn func(context.Context, influxdb.CheckFilter, ...influxdb.FindOptions) ([]influxdb.Check, int, error) FindChecksCalls SafeCount - CreateCheckFn func(context.Context, influxdb.CheckCreate, influxdb.ID) error + CreateCheckFn func(context.Context, influxdb.CheckCreate, platform.ID) error CreateCheckCalls SafeCount - UpdateCheckFn func(context.Context, influxdb.ID, influxdb.CheckCreate) (influxdb.Check, error) + UpdateCheckFn func(context.Context, platform.ID, influxdb.CheckCreate) (influxdb.Check, error) UpdateCheckCalls SafeCount - PatchCheckFn func(context.Context, influxdb.ID, influxdb.CheckUpdate) (influxdb.Check, error) + PatchCheckFn func(context.Context, platform.ID, influxdb.CheckUpdate) (influxdb.Check, error) PatchCheckCalls SafeCount - DeleteCheckFn func(context.Context, influxdb.ID) error + DeleteCheckFn func(context.Context, platform.ID) error DeleteCheckCalls SafeCount } @@ -33,20 +35,20 @@ type CheckService struct { // zero values. func NewCheckService() *CheckService { return &CheckService{ - FindCheckByIDFn: func(context.Context, influxdb.ID) (influxdb.Check, error) { return nil, nil }, + FindCheckByIDFn: func(context.Context, platform.ID) (influxdb.Check, error) { return nil, nil }, FindCheckFn: func(context.Context, influxdb.CheckFilter) (influxdb.Check, error) { return nil, nil }, FindChecksFn: func(context.Context, influxdb.CheckFilter, ...influxdb.FindOptions) ([]influxdb.Check, int, error) { return nil, 0, nil }, - CreateCheckFn: func(context.Context, influxdb.CheckCreate, influxdb.ID) error { return nil }, - UpdateCheckFn: func(context.Context, influxdb.ID, influxdb.CheckCreate) (influxdb.Check, error) { return nil, nil }, - PatchCheckFn: func(context.Context, influxdb.ID, influxdb.CheckUpdate) (influxdb.Check, error) { return nil, nil }, - DeleteCheckFn: func(context.Context, influxdb.ID) error { return nil }, + CreateCheckFn: func(context.Context, influxdb.CheckCreate, platform.ID) error { return nil }, + UpdateCheckFn: func(context.Context, platform.ID, influxdb.CheckCreate) (influxdb.Check, error) { return nil, nil }, + PatchCheckFn: func(context.Context, platform.ID, influxdb.CheckUpdate) (influxdb.Check, error) { return nil, nil }, + DeleteCheckFn: func(context.Context, platform.ID) error { return nil }, } } // FindCheckByID returns a single check by ID. -func (s *CheckService) FindCheckByID(ctx context.Context, id influxdb.ID) (influxdb.Check, error) { +func (s *CheckService) FindCheckByID(ctx context.Context, id platform.ID) (influxdb.Check, error) { defer s.FindCheckByIDCalls.IncrFn()() return s.FindCheckByIDFn(ctx, id) } @@ -64,25 +66,25 @@ func (s *CheckService) FindChecks(ctx context.Context, filter influxdb.CheckFilt } // CreateCheck creates a new check and sets b.ID with the new identifier. -func (s *CheckService) CreateCheck(ctx context.Context, check influxdb.CheckCreate, userID influxdb.ID) error { +func (s *CheckService) CreateCheck(ctx context.Context, check influxdb.CheckCreate, userID platform.ID) error { defer s.CreateCheckCalls.IncrFn()() return s.CreateCheckFn(ctx, check, userID) } // UpdateCheck updates everything except id orgID. -func (s *CheckService) UpdateCheck(ctx context.Context, id influxdb.ID, chk influxdb.CheckCreate) (influxdb.Check, error) { +func (s *CheckService) UpdateCheck(ctx context.Context, id platform.ID, chk influxdb.CheckCreate) (influxdb.Check, error) { defer s.UpdateCheckCalls.IncrFn()() return s.UpdateCheckFn(ctx, id, chk) } // PatchCheck updates a single check with changeset. -func (s *CheckService) PatchCheck(ctx context.Context, id influxdb.ID, upd influxdb.CheckUpdate) (influxdb.Check, error) { +func (s *CheckService) PatchCheck(ctx context.Context, id platform.ID, upd influxdb.CheckUpdate) (influxdb.Check, error) { defer s.PatchCheckCalls.IncrFn()() return s.PatchCheckFn(ctx, id, upd) } // DeleteCheck removes a check by ID. -func (s *CheckService) DeleteCheck(ctx context.Context, id influxdb.ID) error { +func (s *CheckService) DeleteCheck(ctx context.Context, id platform.ID) error { defer s.DeleteCheckCalls.IncrFn()() return s.DeleteCheckFn(ctx, id) } diff --git a/mock/dashboard_service.go b/mock/dashboard_service.go index e3555e155ec..5db6f78d6c3 100644 --- a/mock/dashboard_service.go +++ b/mock/dashboard_service.go @@ -3,6 +3,8 @@ package mock import ( "context" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" ) @@ -11,28 +13,28 @@ var _ platform.DashboardService = &DashboardService{} type DashboardService struct { CreateDashboardF func(context.Context, *platform.Dashboard) error CreateDashboardCalls SafeCount - FindDashboardByIDF func(context.Context, platform.ID) (*platform.Dashboard, error) + FindDashboardByIDF func(context.Context, platform2.ID) (*platform.Dashboard, error) FindDashboardByIDCalls SafeCount FindDashboardsF func(context.Context, platform.DashboardFilter, platform.FindOptions) ([]*platform.Dashboard, int, error) FindDashboardsCalls SafeCount - UpdateDashboardF func(context.Context, platform.ID, platform.DashboardUpdate) (*platform.Dashboard, error) + UpdateDashboardF func(context.Context, platform2.ID, platform.DashboardUpdate) (*platform.Dashboard, error) UpdateDashboardCalls SafeCount - DeleteDashboardF func(context.Context, platform.ID) error + DeleteDashboardF func(context.Context, platform2.ID) error DeleteDashboardCalls SafeCount - AddDashboardCellF func(ctx context.Context, id platform.ID, c *platform.Cell, opts platform.AddDashboardCellOptions) error + AddDashboardCellF func(ctx context.Context, id platform2.ID, c *platform.Cell, opts platform.AddDashboardCellOptions) error AddDashboardCellCalls SafeCount - RemoveDashboardCellF func(ctx context.Context, dashboardID platform.ID, cellID platform.ID) error + RemoveDashboardCellF func(ctx context.Context, dashboardID platform2.ID, cellID platform2.ID) error RemoveDashboardCellCalls SafeCount - GetDashboardCellViewF func(ctx context.Context, dashboardID platform.ID, cellID platform.ID) (*platform.View, error) + GetDashboardCellViewF func(ctx context.Context, dashboardID platform2.ID, cellID platform2.ID) (*platform.View, error) GetDashboardCellViewCalls SafeCount - UpdateDashboardCellViewF func(ctx context.Context, dashboardID platform.ID, cellID platform.ID, upd platform.ViewUpdate) (*platform.View, error) + UpdateDashboardCellViewF func(ctx context.Context, dashboardID platform2.ID, cellID platform2.ID, upd platform.ViewUpdate) (*platform.View, error) UpdateDashboardCellViewCalls SafeCount - UpdateDashboardCellF func(ctx context.Context, dashboardID platform.ID, cellID platform.ID, upd platform.CellUpdate) (*platform.Cell, error) + UpdateDashboardCellF func(ctx context.Context, dashboardID platform2.ID, cellID platform2.ID, upd platform.CellUpdate) (*platform.Cell, error) UpdateDashboardCellCalls SafeCount - CopyDashboardCellF func(ctx context.Context, dashboardID platform.ID, cellID platform.ID) (*platform.Cell, error) + CopyDashboardCellF func(ctx context.Context, dashboardID platform2.ID, cellID platform2.ID) (*platform.Cell, error) CopyDashboardCellCalls SafeCount - ReplaceDashboardCellsF func(ctx context.Context, id platform.ID, cs []*platform.Cell) error + ReplaceDashboardCellsF func(ctx context.Context, id platform2.ID, cs []*platform.Cell) error ReplaceDashboardCellsCalls SafeCount } @@ -40,36 +42,36 @@ type DashboardService struct { func NewDashboardService() *DashboardService { return &DashboardService{ CreateDashboardF: func(context.Context, *platform.Dashboard) error { return nil }, - FindDashboardByIDF: func(context.Context, platform.ID) (*platform.Dashboard, error) { return nil, nil }, + FindDashboardByIDF: func(context.Context, platform2.ID) (*platform.Dashboard, error) { return nil, nil }, FindDashboardsF: func(context.Context, platform.DashboardFilter, platform.FindOptions) ([]*platform.Dashboard, int, error) { return nil, 0, nil }, - UpdateDashboardF: func(context.Context, platform.ID, platform.DashboardUpdate) (*platform.Dashboard, error) { + UpdateDashboardF: func(context.Context, platform2.ID, platform.DashboardUpdate) (*platform.Dashboard, error) { return nil, nil }, - DeleteDashboardF: func(context.Context, platform.ID) error { return nil }, + DeleteDashboardF: func(context.Context, platform2.ID) error { return nil }, - AddDashboardCellF: func(ctx context.Context, id platform.ID, c *platform.Cell, opts platform.AddDashboardCellOptions) error { + AddDashboardCellF: func(ctx context.Context, id platform2.ID, c *platform.Cell, opts platform.AddDashboardCellOptions) error { return nil }, - RemoveDashboardCellF: func(ctx context.Context, dashboardID platform.ID, cellID platform.ID) error { return nil }, - GetDashboardCellViewF: func(ctx context.Context, dashboardID platform.ID, cellID platform.ID) (*platform.View, error) { + RemoveDashboardCellF: func(ctx context.Context, dashboardID platform2.ID, cellID platform2.ID) error { return nil }, + GetDashboardCellViewF: func(ctx context.Context, dashboardID platform2.ID, cellID platform2.ID) (*platform.View, error) { return nil, nil }, - UpdateDashboardCellViewF: func(ctx context.Context, dashboardID platform.ID, cellID platform.ID, upd platform.ViewUpdate) (*platform.View, error) { + UpdateDashboardCellViewF: func(ctx context.Context, dashboardID platform2.ID, cellID platform2.ID, upd platform.ViewUpdate) (*platform.View, error) { return nil, nil }, - UpdateDashboardCellF: func(ctx context.Context, dashboardID platform.ID, cellID platform.ID, upd platform.CellUpdate) (*platform.Cell, error) { + UpdateDashboardCellF: func(ctx context.Context, dashboardID platform2.ID, cellID platform2.ID, upd platform.CellUpdate) (*platform.Cell, error) { return nil, nil }, - CopyDashboardCellF: func(ctx context.Context, dashboardID platform.ID, cellID platform.ID) (*platform.Cell, error) { + CopyDashboardCellF: func(ctx context.Context, dashboardID platform2.ID, cellID platform2.ID) (*platform.Cell, error) { return nil, nil }, - ReplaceDashboardCellsF: func(ctx context.Context, id platform.ID, cs []*platform.Cell) error { return nil }, + ReplaceDashboardCellsF: func(ctx context.Context, id platform2.ID, cs []*platform.Cell) error { return nil }, } } -func (s *DashboardService) FindDashboardByID(ctx context.Context, id platform.ID) (*platform.Dashboard, error) { +func (s *DashboardService) FindDashboardByID(ctx context.Context, id platform2.ID) (*platform.Dashboard, error) { defer s.FindDashboardByIDCalls.IncrFn()() return s.FindDashboardByIDF(ctx, id) } @@ -84,47 +86,47 @@ func (s *DashboardService) CreateDashboard(ctx context.Context, b *platform.Dash return s.CreateDashboardF(ctx, b) } -func (s *DashboardService) UpdateDashboard(ctx context.Context, id platform.ID, upd platform.DashboardUpdate) (*platform.Dashboard, error) { +func (s *DashboardService) UpdateDashboard(ctx context.Context, id platform2.ID, upd platform.DashboardUpdate) (*platform.Dashboard, error) { defer s.UpdateDashboardCalls.IncrFn()() return s.UpdateDashboardF(ctx, id, upd) } -func (s *DashboardService) DeleteDashboard(ctx context.Context, id platform.ID) error { +func (s *DashboardService) DeleteDashboard(ctx context.Context, id platform2.ID) error { defer s.DeleteDashboardCalls.IncrFn()() return s.DeleteDashboardF(ctx, id) } -func (s *DashboardService) GetDashboardCellView(ctx context.Context, dashboardID, cellID platform.ID) (*platform.View, error) { +func (s *DashboardService) GetDashboardCellView(ctx context.Context, dashboardID, cellID platform2.ID) (*platform.View, error) { defer s.GetDashboardCellViewCalls.IncrFn()() return s.GetDashboardCellViewF(ctx, dashboardID, cellID) } -func (s *DashboardService) UpdateDashboardCellView(ctx context.Context, dashboardID, cellID platform.ID, upd platform.ViewUpdate) (*platform.View, error) { +func (s *DashboardService) UpdateDashboardCellView(ctx context.Context, dashboardID, cellID platform2.ID, upd platform.ViewUpdate) (*platform.View, error) { defer s.UpdateDashboardCellViewCalls.IncrFn()() return s.UpdateDashboardCellViewF(ctx, dashboardID, cellID, upd) } -func (s *DashboardService) AddDashboardCell(ctx context.Context, id platform.ID, c *platform.Cell, opts platform.AddDashboardCellOptions) error { +func (s *DashboardService) AddDashboardCell(ctx context.Context, id platform2.ID, c *platform.Cell, opts platform.AddDashboardCellOptions) error { defer s.AddDashboardCellCalls.IncrFn()() return s.AddDashboardCellF(ctx, id, c, opts) } -func (s *DashboardService) ReplaceDashboardCells(ctx context.Context, id platform.ID, cs []*platform.Cell) error { +func (s *DashboardService) ReplaceDashboardCells(ctx context.Context, id platform2.ID, cs []*platform.Cell) error { defer s.ReplaceDashboardCellsCalls.IncrFn()() return s.ReplaceDashboardCellsF(ctx, id, cs) } -func (s *DashboardService) RemoveDashboardCell(ctx context.Context, dashboardID platform.ID, cellID platform.ID) error { +func (s *DashboardService) RemoveDashboardCell(ctx context.Context, dashboardID platform2.ID, cellID platform2.ID) error { defer s.RemoveDashboardCellCalls.IncrFn()() return s.RemoveDashboardCellF(ctx, dashboardID, cellID) } -func (s *DashboardService) UpdateDashboardCell(ctx context.Context, dashboardID platform.ID, cellID platform.ID, upd platform.CellUpdate) (*platform.Cell, error) { +func (s *DashboardService) UpdateDashboardCell(ctx context.Context, dashboardID platform2.ID, cellID platform2.ID, upd platform.CellUpdate) (*platform.Cell, error) { defer s.UpdateDashboardCellCalls.IncrFn()() return s.UpdateDashboardCellF(ctx, dashboardID, cellID, upd) } -func (s *DashboardService) CopyDashboardCell(ctx context.Context, dashboardID platform.ID, cellID platform.ID) (*platform.Cell, error) { +func (s *DashboardService) CopyDashboardCell(ctx context.Context, dashboardID platform2.ID, cellID platform2.ID) (*platform.Cell, error) { defer s.CopyDashboardCellCalls.IncrFn()() return s.CopyDashboardCellF(ctx, dashboardID, cellID) } diff --git a/mock/dbrp_mapping.go b/mock/dbrp_mapping.go index 84486c8bb7f..031a4318aa0 100644 --- a/mock/dbrp_mapping.go +++ b/mock/dbrp_mapping.go @@ -3,20 +3,22 @@ package mock import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) var _ influxdb.DBRPMappingServiceV2 = (*DBRPMappingServiceV2)(nil) type DBRPMappingServiceV2 struct { - FindByIDFn func(ctx context.Context, orgID, id influxdb.ID) (*influxdb.DBRPMappingV2, error) + FindByIDFn func(ctx context.Context, orgID, id platform.ID) (*influxdb.DBRPMappingV2, error) FindManyFn func(ctx context.Context, dbrp influxdb.DBRPMappingFilterV2, opts ...influxdb.FindOptions) ([]*influxdb.DBRPMappingV2, int, error) CreateFn func(ctx context.Context, dbrp *influxdb.DBRPMappingV2) error UpdateFn func(ctx context.Context, dbrp *influxdb.DBRPMappingV2) error - DeleteFn func(ctx context.Context, orgID, id influxdb.ID) error + DeleteFn func(ctx context.Context, orgID, id platform.ID) error } -func (s *DBRPMappingServiceV2) FindByID(ctx context.Context, orgID, id influxdb.ID) (*influxdb.DBRPMappingV2, error) { +func (s *DBRPMappingServiceV2) FindByID(ctx context.Context, orgID, id platform.ID) (*influxdb.DBRPMappingV2, error) { if s.FindByIDFn == nil { return nil, nil } @@ -44,7 +46,7 @@ func (s *DBRPMappingServiceV2) Update(ctx context.Context, dbrp *influxdb.DBRPMa return s.UpdateFn(ctx, dbrp) } -func (s *DBRPMappingServiceV2) Delete(ctx context.Context, orgID, id influxdb.ID) error { +func (s *DBRPMappingServiceV2) Delete(ctx context.Context, orgID, id platform.ID) error { if s.DeleteFn == nil { return nil } diff --git a/mock/delete.go b/mock/delete.go index 7c925f3f18b..8f77819f940 100644 --- a/mock/delete.go +++ b/mock/delete.go @@ -3,6 +3,8 @@ package mock import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -10,20 +12,20 @@ var _ influxdb.DeleteService = &DeleteService{} // DeleteService is a mock delete server. type DeleteService struct { - DeleteBucketRangePredicateF func(tx context.Context, orgID, bucketID influxdb.ID, min, max int64, pred influxdb.Predicate) error + DeleteBucketRangePredicateF func(tx context.Context, orgID, bucketID platform.ID, min, max int64, pred influxdb.Predicate) error } // NewDeleteService returns a mock DeleteService where its methods will return // zero values. func NewDeleteService() DeleteService { return DeleteService{ - DeleteBucketRangePredicateF: func(tx context.Context, orgID, bucketID influxdb.ID, min, max int64, pred influxdb.Predicate) error { + DeleteBucketRangePredicateF: func(tx context.Context, orgID, bucketID platform.ID, min, max int64, pred influxdb.Predicate) error { return nil }, } } //DeleteBucketRangePredicate calls DeleteBucketRangePredicateF. -func (s DeleteService) DeleteBucketRangePredicate(ctx context.Context, orgID, bucketID influxdb.ID, min, max int64, pred influxdb.Predicate) error { +func (s DeleteService) DeleteBucketRangePredicate(ctx context.Context, orgID, bucketID platform.ID, min, max int64, pred influxdb.Predicate) error { return s.DeleteBucketRangePredicateF(ctx, orgID, bucketID, min, max, pred) } diff --git a/mock/dependencies.go b/mock/dependencies.go index 91339c2eb90..27b9cf65b44 100644 --- a/mock/dependencies.go +++ b/mock/dependencies.go @@ -3,20 +3,20 @@ package mock import ( "context" - platform "github.com/influxdata/influxdb/v2" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" ) // BucketLookup implements the BucketLookup interface needed by flux "from" and "to". type BucketLookup struct{} -func (BucketLookup) Lookup(_ context.Context, orgID platform.ID, name string) (platform.ID, bool) { +func (BucketLookup) Lookup(_ context.Context, orgID platform2.ID, name string) (platform2.ID, bool) { if name == "my-bucket" { - return platform.ID(1), true + return platform2.ID(1), true } - return platform.InvalidID(), false + return platform2.InvalidID(), false } -func (BucketLookup) LookupName(_ context.Context, orgID platform.ID, id platform.ID) string { +func (BucketLookup) LookupName(_ context.Context, orgID platform2.ID, id platform2.ID) string { if id == 1 { return "my-bucket" } @@ -26,14 +26,14 @@ func (BucketLookup) LookupName(_ context.Context, orgID platform.ID, id platform // OrganizationLookup implements the OrganizationLookup interface needed by flux "from" and "to". type OrganizationLookup struct{} -func (OrganizationLookup) Lookup(_ context.Context, name string) (platform.ID, bool) { +func (OrganizationLookup) Lookup(_ context.Context, name string) (platform2.ID, bool) { if name == "my-org" { - return platform.ID(2), true + return platform2.ID(2), true } - return platform.InvalidID(), false + return platform2.InvalidID(), false } -func (OrganizationLookup) LookupName(_ context.Context, id platform.ID) string { +func (OrganizationLookup) LookupName(_ context.Context, id platform2.ID) string { if id == 2 { return "my-org" } diff --git a/mock/document_service.go b/mock/document_service.go index d6eeaa1ccc9..a8f5d786fb3 100644 --- a/mock/document_service.go +++ b/mock/document_service.go @@ -3,6 +3,8 @@ package mock import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -40,8 +42,8 @@ func NewDocumentService() *DocumentService { type DocumentStore struct { TimeGenerator TimeGenerator CreateDocumentFn func(ctx context.Context, d *influxdb.Document) error - FindDocumentFn func(ctx context.Context, id influxdb.ID) (*influxdb.Document, error) - FindDocumentsFn func(ctx context.Context, oid influxdb.ID) ([]*influxdb.Document, error) + FindDocumentFn func(ctx context.Context, id platform.ID) (*influxdb.Document, error) + FindDocumentsFn func(ctx context.Context, oid platform.ID) ([]*influxdb.Document, error) } // NewDocumentStore returns a mock of DocumentStore where its methods will return zero values. @@ -50,10 +52,10 @@ func NewDocumentStore() *DocumentStore { CreateDocumentFn: func(ctx context.Context, d *influxdb.Document) error { return nil }, - FindDocumentFn: func(ctx context.Context, id influxdb.ID) (document *influxdb.Document, e error) { + FindDocumentFn: func(ctx context.Context, id platform.ID) (document *influxdb.Document, e error) { return nil, nil }, - FindDocumentsFn: func(ctx context.Context, oid influxdb.ID) ([]*influxdb.Document, error) { + FindDocumentsFn: func(ctx context.Context, oid platform.ID) ([]*influxdb.Document, error) { return nil, nil }, } @@ -65,11 +67,11 @@ func (s *DocumentStore) CreateDocument(ctx context.Context, d *influxdb.Document } // FindDocument will call the mocked FindDocumentFn. -func (s *DocumentStore) FindDocument(ctx context.Context, id influxdb.ID) (*influxdb.Document, error) { +func (s *DocumentStore) FindDocument(ctx context.Context, id platform.ID) (*influxdb.Document, error) { return s.FindDocumentFn(ctx, id) } // FindDocuments will call the mocked FindDocumentsFn. -func (s *DocumentStore) FindDocuments(ctx context.Context, oid influxdb.ID) ([]*influxdb.Document, error) { +func (s *DocumentStore) FindDocuments(ctx context.Context, oid platform.ID) ([]*influxdb.Document, error) { return s.FindDocumentsFn(ctx, oid) } diff --git a/mock/generators.go b/mock/generators.go index 70a8f116a8c..669a883abcb 100644 --- a/mock/generators.go +++ b/mock/generators.go @@ -4,16 +4,16 @@ import ( "testing" "time" - influxdb "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" ) // IDGenerator is mock implementation of influxdb.IDGenerator. type IDGenerator struct { - IDFn func() influxdb.ID + IDFn func() platform.ID } // ID generates a new influxdb.ID from a mock function. -func (g IDGenerator) ID() influxdb.ID { +func (g IDGenerator) ID() platform.ID { return g.IDFn() } @@ -21,7 +21,7 @@ func (g IDGenerator) ID() influxdb.ID { func NewIDGenerator(s string, t *testing.T) IDGenerator { t.Helper() - id, err := influxdb.IDFromString(s) + id, err := platform.IDFromString(s) if err != nil { t.Fatal(err) } @@ -31,9 +31,9 @@ func NewIDGenerator(s string, t *testing.T) IDGenerator { // NewStaticIDGenerator returns an IDGenerator which produces the ID // provided to this function on a call to ID(). -func NewStaticIDGenerator(id influxdb.ID) IDGenerator { +func NewStaticIDGenerator(id platform.ID) IDGenerator { return IDGenerator{ - IDFn: func() influxdb.ID { + IDFn: func() platform.ID { return id }, } @@ -41,9 +41,9 @@ func NewStaticIDGenerator(id influxdb.ID) IDGenerator { // NewIncrementingIDGenerator returns an ID generator which starts at the // provided ID and increments on each call to ID(). -func NewIncrementingIDGenerator(start influxdb.ID) IDGenerator { +func NewIncrementingIDGenerator(start platform.ID) IDGenerator { return IDGenerator{ - IDFn: func() influxdb.ID { + IDFn: func() platform.ID { defer func() { start++ }() return start }, @@ -53,7 +53,7 @@ func NewIncrementingIDGenerator(start influxdb.ID) IDGenerator { // SetIDForFunc replaces the id generator at the end of the pointer with // one which returns the provided id. It then invokes the provided function before // restoring the original value at the end of the pointer. -func SetIDForFunc(gen *influxdb.IDGenerator, id influxdb.ID, fn func()) { +func SetIDForFunc(gen *platform.IDGenerator, id platform.ID, fn func()) { backup := *gen defer func() { *gen = backup }() @@ -63,7 +63,7 @@ func SetIDForFunc(gen *influxdb.IDGenerator, id influxdb.ID, fn func()) { } type MockIDGenerator struct { - Last *influxdb.ID + Last *platform.ID Count int } @@ -75,8 +75,8 @@ func NewMockIDGenerator() *MockIDGenerator { } } -func (g *MockIDGenerator) ID() influxdb.ID { - id := influxdb.ID(g.Count) +func (g *MockIDGenerator) ID() platform.ID { + id := platform.ID(g.Count) g.Count++ g.Last = &id diff --git a/mock/label_service.go b/mock/label_service.go index 8aa717620a2..ed49aee55ba 100644 --- a/mock/label_service.go +++ b/mock/label_service.go @@ -3,6 +3,8 @@ package mock import ( "context" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" ) @@ -12,15 +14,15 @@ var _ platform.LabelService = &LabelService{} type LabelService struct { CreateLabelFn func(context.Context, *platform.Label) error CreateLabelCalls SafeCount - DeleteLabelFn func(context.Context, platform.ID) error + DeleteLabelFn func(context.Context, platform2.ID) error DeleteLabelCalls SafeCount - FindLabelByIDFn func(ctx context.Context, id platform.ID) (*platform.Label, error) + FindLabelByIDFn func(ctx context.Context, id platform2.ID) (*platform.Label, error) FindLabelByIDCalls SafeCount FindLabelsFn func(context.Context, platform.LabelFilter) ([]*platform.Label, error) FindLabelsCalls SafeCount FindResourceLabelsFn func(context.Context, platform.LabelMappingFilter) ([]*platform.Label, error) FindResourceLabelsCalls SafeCount - UpdateLabelFn func(context.Context, platform.ID, platform.LabelUpdate) (*platform.Label, error) + UpdateLabelFn func(context.Context, platform2.ID, platform.LabelUpdate) (*platform.Label, error) UpdateLabelCalls SafeCount CreateLabelMappingFn func(context.Context, *platform.LabelMapping) error CreateLabelMappingCalls SafeCount @@ -32,7 +34,7 @@ type LabelService struct { // where its methods will return zero values. func NewLabelService() *LabelService { return &LabelService{ - FindLabelByIDFn: func(ctx context.Context, id platform.ID) (*platform.Label, error) { + FindLabelByIDFn: func(ctx context.Context, id platform2.ID) (*platform.Label, error) { return nil, nil }, FindLabelsFn: func(context.Context, platform.LabelFilter) ([]*platform.Label, error) { @@ -43,14 +45,14 @@ func NewLabelService() *LabelService { }, CreateLabelFn: func(context.Context, *platform.Label) error { return nil }, CreateLabelMappingFn: func(context.Context, *platform.LabelMapping) error { return nil }, - UpdateLabelFn: func(context.Context, platform.ID, platform.LabelUpdate) (*platform.Label, error) { return nil, nil }, - DeleteLabelFn: func(context.Context, platform.ID) error { return nil }, + UpdateLabelFn: func(context.Context, platform2.ID, platform.LabelUpdate) (*platform.Label, error) { return nil, nil }, + DeleteLabelFn: func(context.Context, platform2.ID) error { return nil }, DeleteLabelMappingFn: func(context.Context, *platform.LabelMapping) error { return nil }, } } // FindLabelByID finds mappings by their ID -func (s *LabelService) FindLabelByID(ctx context.Context, id platform.ID) (*platform.Label, error) { +func (s *LabelService) FindLabelByID(ctx context.Context, id platform2.ID) (*platform.Label, error) { defer s.FindLabelByIDCalls.IncrFn()() return s.FindLabelByIDFn(ctx, id) } @@ -80,13 +82,13 @@ func (s *LabelService) CreateLabelMapping(ctx context.Context, m *platform.Label } // UpdateLabel updates a label. -func (s *LabelService) UpdateLabel(ctx context.Context, id platform.ID, upd platform.LabelUpdate) (*platform.Label, error) { +func (s *LabelService) UpdateLabel(ctx context.Context, id platform2.ID, upd platform.LabelUpdate) (*platform.Label, error) { defer s.UpdateLabelCalls.IncrFn()() return s.UpdateLabelFn(ctx, id, upd) } // DeleteLabel removes a Label. -func (s *LabelService) DeleteLabel(ctx context.Context, id platform.ID) error { +func (s *LabelService) DeleteLabel(ctx context.Context, id platform2.ID) error { defer s.DeleteLabelCalls.IncrFn()() return s.DeleteLabelFn(ctx, id) } diff --git a/mock/lookup_service.go b/mock/lookup_service.go index e4c1a71a47f..a64f75420f1 100644 --- a/mock/lookup_service.go +++ b/mock/lookup_service.go @@ -3,24 +3,26 @@ package mock import ( "context" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" ) // LookupService provides field lookup for the resource and ID. type LookupService struct { - NameFn func(ctx context.Context, resource platform.ResourceType, id platform.ID) (string, error) + NameFn func(ctx context.Context, resource platform.ResourceType, id platform2.ID) (string, error) } // NewLookupService returns a mock of LookupService where its methods will return zero values. func NewLookupService() *LookupService { return &LookupService{ - NameFn: func(ctx context.Context, resource platform.ResourceType, id platform.ID) (string, error) { + NameFn: func(ctx context.Context, resource platform.ResourceType, id platform2.ID) (string, error) { return "", nil }, } } // FindResourceName returns the name for the resource and ID. -func (s *LookupService) FindResourceName(ctx context.Context, resource platform.ResourceType, id platform.ID) (string, error) { +func (s *LookupService) FindResourceName(ctx context.Context, resource platform.ResourceType, id platform2.ID) (string, error) { return s.NameFn(ctx, resource, id) } diff --git a/mock/notification_endpoint_service.go b/mock/notification_endpoint_service.go index 32fe2ec91d8..aba06db7fce 100644 --- a/mock/notification_endpoint_service.go +++ b/mock/notification_endpoint_service.go @@ -3,6 +3,8 @@ package mock import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -12,17 +14,17 @@ var _ influxdb.NotificationEndpointService = &NotificationEndpointService{} type NotificationEndpointService struct { *OrganizationService *UserResourceMappingService - FindNotificationEndpointByIDF func(ctx context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) + FindNotificationEndpointByIDF func(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) FindNotificationEndpointByIDCalls SafeCount FindNotificationEndpointsF func(ctx context.Context, filter influxdb.NotificationEndpointFilter, opt ...influxdb.FindOptions) ([]influxdb.NotificationEndpoint, int, error) FindNotificationEndpointsCalls SafeCount - CreateNotificationEndpointF func(ctx context.Context, nr influxdb.NotificationEndpoint, userID influxdb.ID) error + CreateNotificationEndpointF func(ctx context.Context, nr influxdb.NotificationEndpoint, userID platform.ID) error CreateNotificationEndpointCalls SafeCount - UpdateNotificationEndpointF func(ctx context.Context, id influxdb.ID, nr influxdb.NotificationEndpoint, userID influxdb.ID) (influxdb.NotificationEndpoint, error) + UpdateNotificationEndpointF func(ctx context.Context, id platform.ID, nr influxdb.NotificationEndpoint, userID platform.ID) (influxdb.NotificationEndpoint, error) UpdateNotificationEndpointCalls SafeCount - PatchNotificationEndpointF func(ctx context.Context, id influxdb.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) + PatchNotificationEndpointF func(ctx context.Context, id platform.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) PatchNotificationEndpointCalls SafeCount - DeleteNotificationEndpointF func(ctx context.Context, id influxdb.ID) ([]influxdb.SecretField, influxdb.ID, error) + DeleteNotificationEndpointF func(ctx context.Context, id platform.ID) ([]influxdb.SecretField, platform.ID, error) DeleteNotificationEndpointCalls SafeCount } @@ -30,29 +32,29 @@ func NewNotificationEndpointService() *NotificationEndpointService { return &NotificationEndpointService{ OrganizationService: NewOrganizationService(), UserResourceMappingService: NewUserResourceMappingService(), - FindNotificationEndpointByIDF: func(ctx context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { + FindNotificationEndpointByIDF: func(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { return nil, nil }, FindNotificationEndpointsF: func(ctx context.Context, filter influxdb.NotificationEndpointFilter, opt ...influxdb.FindOptions) ([]influxdb.NotificationEndpoint, int, error) { return nil, 0, nil }, - CreateNotificationEndpointF: func(ctx context.Context, nr influxdb.NotificationEndpoint, userID influxdb.ID) error { + CreateNotificationEndpointF: func(ctx context.Context, nr influxdb.NotificationEndpoint, userID platform.ID) error { return nil }, - UpdateNotificationEndpointF: func(ctx context.Context, id influxdb.ID, nr influxdb.NotificationEndpoint, userID influxdb.ID) (influxdb.NotificationEndpoint, error) { + UpdateNotificationEndpointF: func(ctx context.Context, id platform.ID, nr influxdb.NotificationEndpoint, userID platform.ID) (influxdb.NotificationEndpoint, error) { return nil, nil }, - PatchNotificationEndpointF: func(ctx context.Context, id influxdb.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { + PatchNotificationEndpointF: func(ctx context.Context, id platform.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { return nil, nil }, - DeleteNotificationEndpointF: func(ctx context.Context, id influxdb.ID) ([]influxdb.SecretField, influxdb.ID, error) { + DeleteNotificationEndpointF: func(ctx context.Context, id platform.ID) ([]influxdb.SecretField, platform.ID, error) { return nil, 0, nil }, } } // FindNotificationEndpointByID returns a single telegraf config by ID. -func (s *NotificationEndpointService) FindNotificationEndpointByID(ctx context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { +func (s *NotificationEndpointService) FindNotificationEndpointByID(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { defer s.FindNotificationEndpointByIDCalls.IncrFn()() return s.FindNotificationEndpointByIDF(ctx, id) } @@ -65,27 +67,27 @@ func (s *NotificationEndpointService) FindNotificationEndpoints(ctx context.Cont } // CreateNotificationEndpoint creates a new notification rule and sets ID with the new identifier. -func (s *NotificationEndpointService) CreateNotificationEndpoint(ctx context.Context, nr influxdb.NotificationEndpoint, userID influxdb.ID) error { +func (s *NotificationEndpointService) CreateNotificationEndpoint(ctx context.Context, nr influxdb.NotificationEndpoint, userID platform.ID) error { defer s.CreateNotificationEndpointCalls.IncrFn()() return s.CreateNotificationEndpointF(ctx, nr, userID) } // UpdateNotificationEndpoint updates a single notification rule. // Returns the new notification rule after update. -func (s *NotificationEndpointService) UpdateNotificationEndpoint(ctx context.Context, id influxdb.ID, nr influxdb.NotificationEndpoint, userID influxdb.ID) (influxdb.NotificationEndpoint, error) { +func (s *NotificationEndpointService) UpdateNotificationEndpoint(ctx context.Context, id platform.ID, nr influxdb.NotificationEndpoint, userID platform.ID) (influxdb.NotificationEndpoint, error) { defer s.UpdateNotificationEndpointCalls.IncrFn()() return s.UpdateNotificationEndpointF(ctx, id, nr, userID) } // PatchNotificationEndpoint updates a single notification rule with changeset. // Returns the new notification rule after update. -func (s *NotificationEndpointService) PatchNotificationEndpoint(ctx context.Context, id influxdb.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { +func (s *NotificationEndpointService) PatchNotificationEndpoint(ctx context.Context, id platform.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { defer s.PatchNotificationEndpointCalls.IncrFn()() return s.PatchNotificationEndpointF(ctx, id, upd) } // DeleteNotificationEndpoint removes a notification rule by ID. -func (s *NotificationEndpointService) DeleteNotificationEndpoint(ctx context.Context, id influxdb.ID) ([]influxdb.SecretField, influxdb.ID, error) { +func (s *NotificationEndpointService) DeleteNotificationEndpoint(ctx context.Context, id platform.ID) ([]influxdb.SecretField, platform.ID, error) { defer s.DeleteNotificationEndpointCalls.IncrFn()() return s.DeleteNotificationEndpointF(ctx, id) } diff --git a/mock/notification_rule_store.go b/mock/notification_rule_store.go index 7f12e8b4496..b7691d176ca 100644 --- a/mock/notification_rule_store.go +++ b/mock/notification_rule_store.go @@ -3,6 +3,8 @@ package mock import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -12,17 +14,17 @@ var _ influxdb.NotificationRuleStore = &NotificationRuleStore{} type NotificationRuleStore struct { *OrganizationService *UserResourceMappingService - FindNotificationRuleByIDF func(ctx context.Context, id influxdb.ID) (influxdb.NotificationRule, error) + FindNotificationRuleByIDF func(ctx context.Context, id platform.ID) (influxdb.NotificationRule, error) FindNotificationRuleByIDCalls SafeCount FindNotificationRulesF func(ctx context.Context, filter influxdb.NotificationRuleFilter, opt ...influxdb.FindOptions) ([]influxdb.NotificationRule, int, error) FindNotificationRulesCalls SafeCount - CreateNotificationRuleF func(ctx context.Context, nr influxdb.NotificationRuleCreate, userID influxdb.ID) error + CreateNotificationRuleF func(ctx context.Context, nr influxdb.NotificationRuleCreate, userID platform.ID) error CreateNotificationRuleCalls SafeCount - UpdateNotificationRuleF func(ctx context.Context, id influxdb.ID, nr influxdb.NotificationRuleCreate, userID influxdb.ID) (influxdb.NotificationRule, error) + UpdateNotificationRuleF func(ctx context.Context, id platform.ID, nr influxdb.NotificationRuleCreate, userID platform.ID) (influxdb.NotificationRule, error) UpdateNotificationRuleCalls SafeCount - PatchNotificationRuleF func(ctx context.Context, id influxdb.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) + PatchNotificationRuleF func(ctx context.Context, id platform.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) PatchNotificationRuleCalls SafeCount - DeleteNotificationRuleF func(ctx context.Context, id influxdb.ID) error + DeleteNotificationRuleF func(ctx context.Context, id platform.ID) error DeleteNotificationRuleCalls SafeCount } @@ -31,29 +33,29 @@ func NewNotificationRuleStore() *NotificationRuleStore { return &NotificationRuleStore{ OrganizationService: NewOrganizationService(), UserResourceMappingService: NewUserResourceMappingService(), - FindNotificationRuleByIDF: func(ctx context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { + FindNotificationRuleByIDF: func(ctx context.Context, id platform.ID) (influxdb.NotificationRule, error) { return nil, nil }, FindNotificationRulesF: func(ctx context.Context, f influxdb.NotificationRuleFilter, _ ...influxdb.FindOptions) ([]influxdb.NotificationRule, int, error) { return nil, 0, nil }, - CreateNotificationRuleF: func(ctx context.Context, nr influxdb.NotificationRuleCreate, userID influxdb.ID) error { + CreateNotificationRuleF: func(ctx context.Context, nr influxdb.NotificationRuleCreate, userID platform.ID) error { return nil }, - UpdateNotificationRuleF: func(ctx context.Context, id influxdb.ID, nr influxdb.NotificationRuleCreate, userID influxdb.ID) (influxdb.NotificationRule, error) { + UpdateNotificationRuleF: func(ctx context.Context, id platform.ID, nr influxdb.NotificationRuleCreate, userID platform.ID) (influxdb.NotificationRule, error) { return nil, nil }, - PatchNotificationRuleF: func(ctx context.Context, id influxdb.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { + PatchNotificationRuleF: func(ctx context.Context, id platform.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { return nil, nil }, - DeleteNotificationRuleF: func(ctx context.Context, id influxdb.ID) error { + DeleteNotificationRuleF: func(ctx context.Context, id platform.ID) error { return nil }, } } // FindNotificationRuleByID returns a single telegraf config by ID. -func (s *NotificationRuleStore) FindNotificationRuleByID(ctx context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { +func (s *NotificationRuleStore) FindNotificationRuleByID(ctx context.Context, id platform.ID) (influxdb.NotificationRule, error) { defer s.FindNotificationRuleByIDCalls.IncrFn()() return s.FindNotificationRuleByIDF(ctx, id) } @@ -66,27 +68,27 @@ func (s *NotificationRuleStore) FindNotificationRules(ctx context.Context, filte } // CreateNotificationRule creates a new notification rule and sets ID with the new identifier. -func (s *NotificationRuleStore) CreateNotificationRule(ctx context.Context, nr influxdb.NotificationRuleCreate, userID influxdb.ID) error { +func (s *NotificationRuleStore) CreateNotificationRule(ctx context.Context, nr influxdb.NotificationRuleCreate, userID platform.ID) error { defer s.CreateNotificationRuleCalls.IncrFn()() return s.CreateNotificationRuleF(ctx, nr, userID) } // UpdateNotificationRule updates a single notification rule. // Returns the new notification rule after update. -func (s *NotificationRuleStore) UpdateNotificationRule(ctx context.Context, id influxdb.ID, nr influxdb.NotificationRuleCreate, userID influxdb.ID) (influxdb.NotificationRule, error) { +func (s *NotificationRuleStore) UpdateNotificationRule(ctx context.Context, id platform.ID, nr influxdb.NotificationRuleCreate, userID platform.ID) (influxdb.NotificationRule, error) { defer s.UpdateNotificationRuleCalls.IncrFn()() return s.UpdateNotificationRuleF(ctx, id, nr, userID) } // PatchNotificationRule updates a single notification rule with changeset. // Returns the new notification rule after update. -func (s *NotificationRuleStore) PatchNotificationRule(ctx context.Context, id influxdb.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { +func (s *NotificationRuleStore) PatchNotificationRule(ctx context.Context, id platform.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { defer s.PatchNotificationRuleCalls.IncrFn()() return s.PatchNotificationRuleF(ctx, id, upd) } // DeleteNotificationRule removes a notification rule by ID. -func (s *NotificationRuleStore) DeleteNotificationRule(ctx context.Context, id influxdb.ID) error { +func (s *NotificationRuleStore) DeleteNotificationRule(ctx context.Context, id platform.ID) error { defer s.DeleteNotificationRuleCalls.IncrFn()() return s.DeleteNotificationRuleF(ctx, id) } diff --git a/mock/operation_log_service.go b/mock/operation_log_service.go index 3a698afcba4..377b09c8fe0 100644 --- a/mock/operation_log_service.go +++ b/mock/operation_log_service.go @@ -3,6 +3,8 @@ package mock import ( "context" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" ) @@ -14,7 +16,7 @@ var _ platform.UserOperationLogService = (*UserOperationLogService)(nil) // NewBucketOperationLogService returns a mock of BucketOperationLogService. func NewBucketOperationLogService() *BucketOperationLogService { return &BucketOperationLogService{ - GetBucketOperationLogFn: func(context.Context, platform.ID, platform.FindOptions) ([]*platform.OperationLogEntry, int, error) { + GetBucketOperationLogFn: func(context.Context, platform2.ID, platform.FindOptions) ([]*platform.OperationLogEntry, int, error) { return nil, 0, nil }, } @@ -23,7 +25,7 @@ func NewBucketOperationLogService() *BucketOperationLogService { // NewDashboardOperationLogService returns a mock of DashboardOperationLogService. func NewDashboardOperationLogService() *DashboardOperationLogService { return &DashboardOperationLogService{ - GetDashboardOperationLogFn: func(context.Context, platform.ID, platform.FindOptions) ([]*platform.OperationLogEntry, int, error) { + GetDashboardOperationLogFn: func(context.Context, platform2.ID, platform.FindOptions) ([]*platform.OperationLogEntry, int, error) { return nil, 0, nil }, } @@ -32,7 +34,7 @@ func NewDashboardOperationLogService() *DashboardOperationLogService { // NewOrganizationOperationLogService returns a mock of OrganizationOperationLogService. func NewOrganizationOperationLogService() *OrganizationOperationLogService { return &OrganizationOperationLogService{ - GetOrganizationOperationLogFn: func(context.Context, platform.ID, platform.FindOptions) ([]*platform.OperationLogEntry, int, error) { + GetOrganizationOperationLogFn: func(context.Context, platform2.ID, platform.FindOptions) ([]*platform.OperationLogEntry, int, error) { return nil, 0, nil }, } @@ -41,7 +43,7 @@ func NewOrganizationOperationLogService() *OrganizationOperationLogService { // NewUserOperationLogService returns a mock of UserOperationLogService. func NewUserOperationLogService() *UserOperationLogService { return &UserOperationLogService{ - GetUserOperationLogFn: func(context.Context, platform.ID, platform.FindOptions) ([]*platform.OperationLogEntry, int, error) { + GetUserOperationLogFn: func(context.Context, platform2.ID, platform.FindOptions) ([]*platform.OperationLogEntry, int, error) { return nil, 0, nil }, } @@ -49,40 +51,40 @@ func NewUserOperationLogService() *UserOperationLogService { // BucketOperationLogService is a mock implementation of platform.BucketOperationLogService. type BucketOperationLogService struct { - GetBucketOperationLogFn func(context.Context, platform.ID, platform.FindOptions) ([]*platform.OperationLogEntry, int, error) + GetBucketOperationLogFn func(context.Context, platform2.ID, platform.FindOptions) ([]*platform.OperationLogEntry, int, error) } // DashboardOperationLogService is a mock implementation of platform.DashboardOperationLogService. type DashboardOperationLogService struct { - GetDashboardOperationLogFn func(context.Context, platform.ID, platform.FindOptions) ([]*platform.OperationLogEntry, int, error) + GetDashboardOperationLogFn func(context.Context, platform2.ID, platform.FindOptions) ([]*platform.OperationLogEntry, int, error) } // OrganizationOperationLogService is a mock implementation of platform.OrganizationOperationLogService. type OrganizationOperationLogService struct { - GetOrganizationOperationLogFn func(context.Context, platform.ID, platform.FindOptions) ([]*platform.OperationLogEntry, int, error) + GetOrganizationOperationLogFn func(context.Context, platform2.ID, platform.FindOptions) ([]*platform.OperationLogEntry, int, error) } // UserOperationLogService is a mock implementation of platform.UserOperationLogService. type UserOperationLogService struct { - GetUserOperationLogFn func(context.Context, platform.ID, platform.FindOptions) ([]*platform.OperationLogEntry, int, error) + GetUserOperationLogFn func(context.Context, platform2.ID, platform.FindOptions) ([]*platform.OperationLogEntry, int, error) } // GetBucketOperationLog retrieves the operation log for the bucket with the provided id. -func (s *BucketOperationLogService) GetBucketOperationLog(ctx context.Context, id platform.ID, opts platform.FindOptions) ([]*platform.OperationLogEntry, int, error) { +func (s *BucketOperationLogService) GetBucketOperationLog(ctx context.Context, id platform2.ID, opts platform.FindOptions) ([]*platform.OperationLogEntry, int, error) { return s.GetBucketOperationLogFn(ctx, id, opts) } // GetDashboardOperationLog retrieves the operation log for the dashboard with the provided id. -func (s *DashboardOperationLogService) GetDashboardOperationLog(ctx context.Context, id platform.ID, opts platform.FindOptions) ([]*platform.OperationLogEntry, int, error) { +func (s *DashboardOperationLogService) GetDashboardOperationLog(ctx context.Context, id platform2.ID, opts platform.FindOptions) ([]*platform.OperationLogEntry, int, error) { return s.GetDashboardOperationLogFn(ctx, id, opts) } // GetOrganizationOperationLog retrieves the operation log for the org with the provided id. -func (s *OrganizationOperationLogService) GetOrganizationOperationLog(ctx context.Context, id platform.ID, opts platform.FindOptions) ([]*platform.OperationLogEntry, int, error) { +func (s *OrganizationOperationLogService) GetOrganizationOperationLog(ctx context.Context, id platform2.ID, opts platform.FindOptions) ([]*platform.OperationLogEntry, int, error) { return s.GetOrganizationOperationLogFn(ctx, id, opts) } // GetUserOperationLog retrieves the operation log for the user with the provided id. -func (s *UserOperationLogService) GetUserOperationLog(ctx context.Context, id platform.ID, opts platform.FindOptions) ([]*platform.OperationLogEntry, int, error) { +func (s *UserOperationLogService) GetUserOperationLog(ctx context.Context, id platform2.ID, opts platform.FindOptions) ([]*platform.OperationLogEntry, int, error) { return s.GetUserOperationLogFn(ctx, id, opts) } diff --git a/mock/org_service.go b/mock/org_service.go index e878881d677..daf8741d352 100644 --- a/mock/org_service.go +++ b/mock/org_service.go @@ -3,6 +3,8 @@ package mock import ( "context" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" ) @@ -10,20 +12,20 @@ var _ platform.OrganizationService = &OrganizationService{} // OrganizationService is a mock organization server. type OrganizationService struct { - FindOrganizationByIDF func(ctx context.Context, id platform.ID) (*platform.Organization, error) + FindOrganizationByIDF func(ctx context.Context, id platform2.ID) (*platform.Organization, error) FindOrganizationF func(ctx context.Context, filter platform.OrganizationFilter) (*platform.Organization, error) FindOrganizationsF func(ctx context.Context, filter platform.OrganizationFilter, opt ...platform.FindOptions) ([]*platform.Organization, int, error) CreateOrganizationF func(ctx context.Context, b *platform.Organization) error - UpdateOrganizationF func(ctx context.Context, id platform.ID, upd platform.OrganizationUpdate) (*platform.Organization, error) - DeleteOrganizationF func(ctx context.Context, id platform.ID) error - FindResourceOrganizationIDF func(ctx context.Context, rt platform.ResourceType, id platform.ID) (platform.ID, error) + UpdateOrganizationF func(ctx context.Context, id platform2.ID, upd platform.OrganizationUpdate) (*platform.Organization, error) + DeleteOrganizationF func(ctx context.Context, id platform2.ID) error + FindResourceOrganizationIDF func(ctx context.Context, rt platform.ResourceType, id platform2.ID) (platform2.ID, error) } // NewOrganizationService returns a mock OrganizationService where its methods will return // zero values. func NewOrganizationService() *OrganizationService { return &OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*platform.Organization, error) { return nil, nil }, + FindOrganizationByIDF: func(ctx context.Context, id platform2.ID) (*platform.Organization, error) { return nil, nil }, FindOrganizationF: func(ctx context.Context, filter platform.OrganizationFilter) (*platform.Organization, error) { return nil, nil }, @@ -31,15 +33,15 @@ func NewOrganizationService() *OrganizationService { return nil, 0, nil }, CreateOrganizationF: func(ctx context.Context, b *platform.Organization) error { return nil }, - UpdateOrganizationF: func(ctx context.Context, id platform.ID, upd platform.OrganizationUpdate) (*platform.Organization, error) { + UpdateOrganizationF: func(ctx context.Context, id platform2.ID, upd platform.OrganizationUpdate) (*platform.Organization, error) { return nil, nil }, - DeleteOrganizationF: func(ctx context.Context, id platform.ID) error { return nil }, + DeleteOrganizationF: func(ctx context.Context, id platform2.ID) error { return nil }, } } //FindOrganizationByID calls FindOrganizationByIDF. -func (s *OrganizationService) FindOrganizationByID(ctx context.Context, id platform.ID) (*platform.Organization, error) { +func (s *OrganizationService) FindOrganizationByID(ctx context.Context, id platform2.ID) (*platform.Organization, error) { return s.FindOrganizationByIDF(ctx, id) } @@ -59,16 +61,16 @@ func (s *OrganizationService) CreateOrganization(ctx context.Context, b *platfor } // UpdateOrganization calls UpdateOrganizationF. -func (s *OrganizationService) UpdateOrganization(ctx context.Context, id platform.ID, upd platform.OrganizationUpdate) (*platform.Organization, error) { +func (s *OrganizationService) UpdateOrganization(ctx context.Context, id platform2.ID, upd platform.OrganizationUpdate) (*platform.Organization, error) { return s.UpdateOrganizationF(ctx, id, upd) } // DeleteOrganization calls DeleteOrganizationF. -func (s *OrganizationService) DeleteOrganization(ctx context.Context, id platform.ID) error { +func (s *OrganizationService) DeleteOrganization(ctx context.Context, id platform2.ID) error { return s.DeleteOrganizationF(ctx, id) } // FindResourceOrganizationID calls FindResourceOrganizationIDF. -func (s *OrganizationService) FindResourceOrganizationID(ctx context.Context, rt platform.ResourceType, id platform.ID) (platform.ID, error) { +func (s *OrganizationService) FindResourceOrganizationID(ctx context.Context, rt platform.ResourceType, id platform2.ID) (platform2.ID, error) { return s.FindResourceOrganizationIDF(ctx, rt, id) } diff --git a/mock/passwords.go b/mock/passwords.go index ffd866af7b7..552fc19481e 100644 --- a/mock/passwords.go +++ b/mock/passwords.go @@ -4,38 +4,38 @@ import ( "context" "fmt" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" ) // PasswordsService is a mock implementation of a retention.PasswordsService, which // also makes it a suitable mock to use wherever an platform.PasswordsService is required. type PasswordsService struct { - SetPasswordFn func(context.Context, influxdb.ID, string) error - ComparePasswordFn func(context.Context, influxdb.ID, string) error - CompareAndSetPasswordFn func(context.Context, influxdb.ID, string, string) error + SetPasswordFn func(context.Context, platform.ID, string) error + ComparePasswordFn func(context.Context, platform.ID, string) error + CompareAndSetPasswordFn func(context.Context, platform.ID, string, string) error } // NewPasswordsService returns a mock PasswordsService where its methods will return // zero values. func NewPasswordsService() *PasswordsService { return &PasswordsService{ - SetPasswordFn: func(context.Context, influxdb.ID, string) error { return fmt.Errorf("mock error") }, - ComparePasswordFn: func(context.Context, influxdb.ID, string) error { return fmt.Errorf("mock error") }, - CompareAndSetPasswordFn: func(context.Context, influxdb.ID, string, string) error { return fmt.Errorf("mock error") }, + SetPasswordFn: func(context.Context, platform.ID, string) error { return fmt.Errorf("mock error") }, + ComparePasswordFn: func(context.Context, platform.ID, string) error { return fmt.Errorf("mock error") }, + CompareAndSetPasswordFn: func(context.Context, platform.ID, string, string) error { return fmt.Errorf("mock error") }, } } // SetPassword sets the users current password to be the provided password. -func (s *PasswordsService) SetPassword(ctx context.Context, userID influxdb.ID, password string) error { +func (s *PasswordsService) SetPassword(ctx context.Context, userID platform.ID, password string) error { return s.SetPasswordFn(ctx, userID, password) } // ComparePassword password compares the provided password. -func (s *PasswordsService) ComparePassword(ctx context.Context, userID influxdb.ID, password string) error { +func (s *PasswordsService) ComparePassword(ctx context.Context, userID platform.ID, password string) error { return s.ComparePasswordFn(ctx, userID, password) } // CompareAndSetPassword compares the provided password and sets it to the new password. -func (s *PasswordsService) CompareAndSetPassword(ctx context.Context, userID influxdb.ID, old string, new string) error { +func (s *PasswordsService) CompareAndSetPassword(ctx context.Context, userID platform.ID, old string, new string) error { return s.CompareAndSetPasswordFn(ctx, userID, old, new) } diff --git a/mock/passwords_service.go b/mock/passwords_service.go index 36c352e22e6..70b8604333e 100644 --- a/mock/passwords_service.go +++ b/mock/passwords_service.go @@ -7,7 +7,7 @@ package mock import ( context "context" gomock "github.com/golang/mock/gomock" - influxdb "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" reflect "reflect" ) @@ -35,7 +35,7 @@ func (m *MockPasswordsService) EXPECT() *MockPasswordsServiceMockRecorder { } // CompareAndSetPassword mocks base method -func (m *MockPasswordsService) CompareAndSetPassword(arg0 context.Context, arg1 influxdb.ID, arg2, arg3 string) error { +func (m *MockPasswordsService) CompareAndSetPassword(arg0 context.Context, arg1 platform.ID, arg2, arg3 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CompareAndSetPassword", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(error) @@ -49,7 +49,7 @@ func (mr *MockPasswordsServiceMockRecorder) CompareAndSetPassword(arg0, arg1, ar } // ComparePassword mocks base method -func (m *MockPasswordsService) ComparePassword(arg0 context.Context, arg1 influxdb.ID, arg2 string) error { +func (m *MockPasswordsService) ComparePassword(arg0 context.Context, arg1 platform.ID, arg2 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ComparePassword", arg0, arg1, arg2) ret0, _ := ret[0].(error) @@ -63,7 +63,7 @@ func (mr *MockPasswordsServiceMockRecorder) ComparePassword(arg0, arg1, arg2 int } // SetPassword mocks base method -func (m *MockPasswordsService) SetPassword(arg0 context.Context, arg1 influxdb.ID, arg2 string) error { +func (m *MockPasswordsService) SetPassword(arg0 context.Context, arg1 platform.ID, arg2 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetPassword", arg0, arg1, arg2) ret0, _ := ret[0].(error) diff --git a/mock/points_writer.go b/mock/points_writer.go index 5c779c15536..78d13ea0147 100644 --- a/mock/points_writer.go +++ b/mock/points_writer.go @@ -4,7 +4,8 @@ import ( "context" "sync" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/models" ) @@ -15,7 +16,7 @@ type PointsWriter struct { Points []models.Point Err error - WritePointsFn func(ctx context.Context, orgID influxdb.ID, bucketID influxdb.ID, points []models.Point) error + WritePointsFn func(ctx context.Context, orgID platform.ID, bucketID platform.ID, points []models.Point) error } // ForceError is for error testing, if WritePoints is called after ForceError, it will return that error. @@ -26,7 +27,7 @@ func (p *PointsWriter) ForceError(err error) { } // WritePoints writes points to the PointsWriter that will be exposed in the Values. -func (p *PointsWriter) WritePoints(ctx context.Context, orgID influxdb.ID, bucketID influxdb.ID, points []models.Point) error { +func (p *PointsWriter) WritePoints(ctx context.Context, orgID platform.ID, bucketID platform.ID, points []models.Point) error { if p.WritePointsFn != nil { return p.WritePointsFn(ctx, orgID, bucketID, points) } diff --git a/mock/scraper_service.go b/mock/scraper_service.go index 54acb55379a..ff9c9a4774c 100644 --- a/mock/scraper_service.go +++ b/mock/scraper_service.go @@ -3,6 +3,8 @@ package mock import ( "context" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" ) @@ -13,10 +15,10 @@ type ScraperTargetStoreService struct { UserResourceMappingService OrganizationService ListTargetsF func(ctx context.Context, filter platform.ScraperTargetFilter) ([]platform.ScraperTarget, error) - AddTargetF func(ctx context.Context, t *platform.ScraperTarget, userID platform.ID) error - GetTargetByIDF func(ctx context.Context, id platform.ID) (*platform.ScraperTarget, error) - RemoveTargetF func(ctx context.Context, id platform.ID) error - UpdateTargetF func(ctx context.Context, t *platform.ScraperTarget, userID platform.ID) (*platform.ScraperTarget, error) + AddTargetF func(ctx context.Context, t *platform.ScraperTarget, userID platform2.ID) error + GetTargetByIDF func(ctx context.Context, id platform2.ID) (*platform.ScraperTarget, error) + RemoveTargetF func(ctx context.Context, id platform2.ID) error + UpdateTargetF func(ctx context.Context, t *platform.ScraperTarget, userID platform2.ID) (*platform.ScraperTarget, error) } // ListTargets lists all the scraper targets. @@ -25,21 +27,21 @@ func (s *ScraperTargetStoreService) ListTargets(ctx context.Context, filter plat } // AddTarget adds a scraper target. -func (s *ScraperTargetStoreService) AddTarget(ctx context.Context, t *platform.ScraperTarget, userID platform.ID) error { +func (s *ScraperTargetStoreService) AddTarget(ctx context.Context, t *platform.ScraperTarget, userID platform2.ID) error { return s.AddTargetF(ctx, t, userID) } // GetTargetByID retrieves a scraper target by id. -func (s *ScraperTargetStoreService) GetTargetByID(ctx context.Context, id platform.ID) (*platform.ScraperTarget, error) { +func (s *ScraperTargetStoreService) GetTargetByID(ctx context.Context, id platform2.ID) (*platform.ScraperTarget, error) { return s.GetTargetByIDF(ctx, id) } // RemoveTarget deletes a scraper target. -func (s *ScraperTargetStoreService) RemoveTarget(ctx context.Context, id platform.ID) error { +func (s *ScraperTargetStoreService) RemoveTarget(ctx context.Context, id platform2.ID) error { return s.RemoveTargetF(ctx, id) } // UpdateTarget updates a scraper target. -func (s *ScraperTargetStoreService) UpdateTarget(ctx context.Context, t *platform.ScraperTarget, userID platform.ID) (*platform.ScraperTarget, error) { +func (s *ScraperTargetStoreService) UpdateTarget(ctx context.Context, t *platform.ScraperTarget, userID platform2.ID) (*platform.ScraperTarget, error) { return s.UpdateTargetF(ctx, t, userID) } diff --git a/mock/secret_service.go b/mock/secret_service.go index d57b0bd92b6..07e45eddc55 100644 --- a/mock/secret_service.go +++ b/mock/secret_service.go @@ -4,71 +4,71 @@ import ( "context" "fmt" - platform "github.com/influxdata/influxdb/v2" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" ) // SecretService is a mock implementation of a retention.SecretService, which // also makes it a suitable mock to use wherever an platform.SecretService is required. type SecretService struct { - LoadSecretFn func(ctx context.Context, orgID platform.ID, k string) (string, error) - GetSecretKeysFn func(ctx context.Context, orgID platform.ID) ([]string, error) - PutSecretFn func(ctx context.Context, orgID platform.ID, k string, v string) error - PutSecretsFn func(ctx context.Context, orgID platform.ID, m map[string]string) error - PatchSecretsFn func(ctx context.Context, orgID platform.ID, m map[string]string) error - DeleteSecretFn func(ctx context.Context, orgID platform.ID, ks ...string) error + LoadSecretFn func(ctx context.Context, orgID platform2.ID, k string) (string, error) + GetSecretKeysFn func(ctx context.Context, orgID platform2.ID) ([]string, error) + PutSecretFn func(ctx context.Context, orgID platform2.ID, k string, v string) error + PutSecretsFn func(ctx context.Context, orgID platform2.ID, m map[string]string) error + PatchSecretsFn func(ctx context.Context, orgID platform2.ID, m map[string]string) error + DeleteSecretFn func(ctx context.Context, orgID platform2.ID, ks ...string) error } // NewSecretService returns a mock SecretService where its methods will return // zero values. func NewSecretService() *SecretService { return &SecretService{ - LoadSecretFn: func(ctx context.Context, orgID platform.ID, k string) (string, error) { + LoadSecretFn: func(ctx context.Context, orgID platform2.ID, k string) (string, error) { return "", fmt.Errorf("not implmemented") }, - GetSecretKeysFn: func(ctx context.Context, orgID platform.ID) ([]string, error) { + GetSecretKeysFn: func(ctx context.Context, orgID platform2.ID) ([]string, error) { return nil, fmt.Errorf("not implmemented") }, - PutSecretFn: func(ctx context.Context, orgID platform.ID, k string, v string) error { + PutSecretFn: func(ctx context.Context, orgID platform2.ID, k string, v string) error { return fmt.Errorf("not implmemented") }, - PutSecretsFn: func(ctx context.Context, orgID platform.ID, m map[string]string) error { + PutSecretsFn: func(ctx context.Context, orgID platform2.ID, m map[string]string) error { return fmt.Errorf("not implmemented") }, - PatchSecretsFn: func(ctx context.Context, orgID platform.ID, m map[string]string) error { + PatchSecretsFn: func(ctx context.Context, orgID platform2.ID, m map[string]string) error { return fmt.Errorf("not implmemented") }, - DeleteSecretFn: func(ctx context.Context, orgID platform.ID, ks ...string) error { + DeleteSecretFn: func(ctx context.Context, orgID platform2.ID, ks ...string) error { return fmt.Errorf("not implmemented") }, } } // LoadSecret retrieves the secret value v found at key k for organization orgID. -func (s *SecretService) LoadSecret(ctx context.Context, orgID platform.ID, k string) (string, error) { +func (s *SecretService) LoadSecret(ctx context.Context, orgID platform2.ID, k string) (string, error) { return s.LoadSecretFn(ctx, orgID, k) } // GetSecretKeys retrieves all secret keys that are stored for the organization orgID. -func (s *SecretService) GetSecretKeys(ctx context.Context, orgID platform.ID) ([]string, error) { +func (s *SecretService) GetSecretKeys(ctx context.Context, orgID platform2.ID) ([]string, error) { return s.GetSecretKeysFn(ctx, orgID) } // PutSecret stores the secret pair (k,v) for the organization orgID. -func (s *SecretService) PutSecret(ctx context.Context, orgID platform.ID, k string, v string) error { +func (s *SecretService) PutSecret(ctx context.Context, orgID platform2.ID, k string, v string) error { return s.PutSecretFn(ctx, orgID, k, v) } // PutSecrets puts all provided secrets and overwrites any previous values. -func (s *SecretService) PutSecrets(ctx context.Context, orgID platform.ID, m map[string]string) error { +func (s *SecretService) PutSecrets(ctx context.Context, orgID platform2.ID, m map[string]string) error { return s.PutSecretsFn(ctx, orgID, m) } // PatchSecrets patches all provided secrets and updates any previous values. -func (s *SecretService) PatchSecrets(ctx context.Context, orgID platform.ID, m map[string]string) error { +func (s *SecretService) PatchSecrets(ctx context.Context, orgID platform2.ID, m map[string]string) error { return s.PatchSecretsFn(ctx, orgID, m) } // DeleteSecret removes a single secret from the secret store. -func (s *SecretService) DeleteSecret(ctx context.Context, orgID platform.ID, ks ...string) error { +func (s *SecretService) DeleteSecret(ctx context.Context, orgID platform2.ID, ks ...string) error { return s.DeleteSecretFn(ctx, orgID, ks...) } diff --git a/mock/source_service.go b/mock/source_service.go index 80d6a7b0155..413c6d08b24 100644 --- a/mock/source_service.go +++ b/mock/source_service.go @@ -3,6 +3,8 @@ package mock import ( "context" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" ) @@ -11,21 +13,21 @@ var _ platform.SourceService = (*SourceService)(nil) // SourceService is a mock implementation of platform.SourceService. type SourceService struct { DefaultSourceFn func(context.Context) (*platform.Source, error) - FindSourceByIDFn func(context.Context, platform.ID) (*platform.Source, error) + FindSourceByIDFn func(context.Context, platform2.ID) (*platform.Source, error) FindSourcesFn func(context.Context, platform.FindOptions) ([]*platform.Source, int, error) CreateSourceFn func(context.Context, *platform.Source) error - UpdateSourceFn func(context.Context, platform.ID, platform.SourceUpdate) (*platform.Source, error) - DeleteSourceFn func(context.Context, platform.ID) error + UpdateSourceFn func(context.Context, platform2.ID, platform.SourceUpdate) (*platform.Source, error) + DeleteSourceFn func(context.Context, platform2.ID) error } // NewSourceService returns a mock of SourceService where its methods will return zero values. func NewSourceService() *SourceService { return &SourceService{ DefaultSourceFn: func(context.Context) (*platform.Source, error) { return nil, nil }, - FindSourceByIDFn: func(context.Context, platform.ID) (*platform.Source, error) { return nil, nil }, + FindSourceByIDFn: func(context.Context, platform2.ID) (*platform.Source, error) { return nil, nil }, CreateSourceFn: func(context.Context, *platform.Source) error { return nil }, - UpdateSourceFn: func(context.Context, platform.ID, platform.SourceUpdate) (*platform.Source, error) { return nil, nil }, - DeleteSourceFn: func(context.Context, platform.ID) error { return nil }, + UpdateSourceFn: func(context.Context, platform2.ID, platform.SourceUpdate) (*platform.Source, error) { return nil, nil }, + DeleteSourceFn: func(context.Context, platform2.ID) error { return nil }, FindSourcesFn: func(context.Context, platform.FindOptions) ([]*platform.Source, int, error) { return nil, 0, nil }, @@ -38,7 +40,7 @@ func (s *SourceService) DefaultSource(ctx context.Context) (*platform.Source, er } // FindSourceByID retrieves a source by its ID. -func (s *SourceService) FindSourceByID(ctx context.Context, id platform.ID) (*platform.Source, error) { +func (s *SourceService) FindSourceByID(ctx context.Context, id platform2.ID) (*platform.Source, error) { return s.FindSourceByIDFn(ctx, id) } @@ -53,11 +55,11 @@ func (s *SourceService) CreateSource(ctx context.Context, source *platform.Sourc } // DeleteSource removes the source. -func (s *SourceService) DeleteSource(ctx context.Context, id platform.ID) error { +func (s *SourceService) DeleteSource(ctx context.Context, id platform2.ID) error { return s.DeleteSourceFn(ctx, id) } // UpdateSource updates the source. -func (s *SourceService) UpdateSource(ctx context.Context, id platform.ID, upd platform.SourceUpdate) (*platform.Source, error) { +func (s *SourceService) UpdateSource(ctx context.Context, id platform2.ID, upd platform.SourceUpdate) (*platform.Source, error) { return s.UpdateSourceFn(ctx, id, upd) } diff --git a/mock/task_service.go b/mock/task_service.go index 9ebc34b9db2..b2d18e951ce 100644 --- a/mock/task_service.go +++ b/mock/task_service.go @@ -4,6 +4,8 @@ import ( "context" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/task/backend" ) @@ -12,33 +14,33 @@ var _ influxdb.TaskService = (*TaskService)(nil) var _ backend.TaskControlService = (*TaskControlService)(nil) type TaskService struct { - FindTaskByIDFn func(context.Context, influxdb.ID) (*influxdb.Task, error) + FindTaskByIDFn func(context.Context, platform.ID) (*influxdb.Task, error) FindTaskByIDCalls SafeCount FindTasksFn func(context.Context, influxdb.TaskFilter) ([]*influxdb.Task, int, error) FindTasksCalls SafeCount CreateTaskFn func(context.Context, influxdb.TaskCreate) (*influxdb.Task, error) CreateTaskCalls SafeCount - UpdateTaskFn func(context.Context, influxdb.ID, influxdb.TaskUpdate) (*influxdb.Task, error) + UpdateTaskFn func(context.Context, platform.ID, influxdb.TaskUpdate) (*influxdb.Task, error) UpdateTaskCalls SafeCount - DeleteTaskFn func(context.Context, influxdb.ID) error + DeleteTaskFn func(context.Context, platform.ID) error DeleteTaskCalls SafeCount FindLogsFn func(context.Context, influxdb.LogFilter) ([]*influxdb.Log, int, error) FindLogsCalls SafeCount FindRunsFn func(context.Context, influxdb.RunFilter) ([]*influxdb.Run, int, error) FindRunsCalls SafeCount - FindRunByIDFn func(context.Context, influxdb.ID, influxdb.ID) (*influxdb.Run, error) + FindRunByIDFn func(context.Context, platform.ID, platform.ID) (*influxdb.Run, error) FindRunByIDCalls SafeCount - CancelRunFn func(context.Context, influxdb.ID, influxdb.ID) error + CancelRunFn func(context.Context, platform.ID, platform.ID) error CancelRunCalls SafeCount - RetryRunFn func(context.Context, influxdb.ID, influxdb.ID) (*influxdb.Run, error) + RetryRunFn func(context.Context, platform.ID, platform.ID) (*influxdb.Run, error) RetryRunCalls SafeCount - ForceRunFn func(context.Context, influxdb.ID, int64) (*influxdb.Run, error) + ForceRunFn func(context.Context, platform.ID, int64) (*influxdb.Run, error) ForceRunCalls SafeCount } func NewTaskService() *TaskService { return &TaskService{ - FindTaskByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + FindTaskByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { return nil, nil }, FindTasksFn: func(ctx context.Context, f influxdb.TaskFilter) ([]*influxdb.Task, int, error) { @@ -47,10 +49,10 @@ func NewTaskService() *TaskService { CreateTaskFn: func(ctx context.Context, taskCreate influxdb.TaskCreate) (*influxdb.Task, error) { return nil, nil }, - UpdateTaskFn: func(ctx context.Context, id influxdb.ID, update influxdb.TaskUpdate) (*influxdb.Task, error) { + UpdateTaskFn: func(ctx context.Context, id platform.ID, update influxdb.TaskUpdate) (*influxdb.Task, error) { return nil, nil }, - DeleteTaskFn: func(ctx context.Context, id influxdb.ID) error { + DeleteTaskFn: func(ctx context.Context, id platform.ID) error { return nil }, FindLogsFn: func(ctx context.Context, f influxdb.LogFilter) ([]*influxdb.Log, int, error) { @@ -59,22 +61,22 @@ func NewTaskService() *TaskService { FindRunsFn: func(ctx context.Context, f influxdb.RunFilter) ([]*influxdb.Run, int, error) { return nil, 0, nil }, - FindRunByIDFn: func(ctx context.Context, id influxdb.ID, id2 influxdb.ID) (*influxdb.Run, error) { + FindRunByIDFn: func(ctx context.Context, id platform.ID, id2 platform.ID) (*influxdb.Run, error) { return nil, nil }, - CancelRunFn: func(ctx context.Context, id influxdb.ID, id2 influxdb.ID) error { + CancelRunFn: func(ctx context.Context, id platform.ID, id2 platform.ID) error { return nil }, - RetryRunFn: func(ctx context.Context, id influxdb.ID, id2 influxdb.ID) (*influxdb.Run, error) { + RetryRunFn: func(ctx context.Context, id platform.ID, id2 platform.ID) (*influxdb.Run, error) { return nil, nil }, - ForceRunFn: func(ctx context.Context, id influxdb.ID, i int64) (*influxdb.Run, error) { + ForceRunFn: func(ctx context.Context, id platform.ID, i int64) (*influxdb.Run, error) { return nil, nil }, } } -func (s *TaskService) FindTaskByID(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { +func (s *TaskService) FindTaskByID(ctx context.Context, id platform.ID) (*influxdb.Task, error) { defer s.FindTaskByIDCalls.IncrFn()() return s.FindTaskByIDFn(ctx, id) } @@ -89,12 +91,12 @@ func (s *TaskService) CreateTask(ctx context.Context, t influxdb.TaskCreate) (*i return s.CreateTaskFn(ctx, t) } -func (s *TaskService) UpdateTask(ctx context.Context, id influxdb.ID, upd influxdb.TaskUpdate) (*influxdb.Task, error) { +func (s *TaskService) UpdateTask(ctx context.Context, id platform.ID, upd influxdb.TaskUpdate) (*influxdb.Task, error) { defer s.UpdateTaskCalls.IncrFn()() return s.UpdateTaskFn(ctx, id, upd) } -func (s *TaskService) DeleteTask(ctx context.Context, id influxdb.ID) error { +func (s *TaskService) DeleteTask(ctx context.Context, id platform.ID) error { defer s.DeleteTaskCalls.IncrFn()() return s.DeleteTaskFn(ctx, id) } @@ -109,54 +111,54 @@ func (s *TaskService) FindRuns(ctx context.Context, filter influxdb.RunFilter) ( return s.FindRunsFn(ctx, filter) } -func (s *TaskService) FindRunByID(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (s *TaskService) FindRunByID(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { defer s.FindRunByIDCalls.IncrFn()() return s.FindRunByIDFn(ctx, taskID, runID) } -func (s *TaskService) CancelRun(ctx context.Context, taskID, runID influxdb.ID) error { +func (s *TaskService) CancelRun(ctx context.Context, taskID, runID platform.ID) error { defer s.CancelRunCalls.IncrFn()() return s.CancelRunFn(ctx, taskID, runID) } -func (s *TaskService) RetryRun(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (s *TaskService) RetryRun(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { defer s.RetryRunCalls.IncrFn()() return s.RetryRunFn(ctx, taskID, runID) } -func (s *TaskService) ForceRun(ctx context.Context, taskID influxdb.ID, scheduledFor int64) (*influxdb.Run, error) { +func (s *TaskService) ForceRun(ctx context.Context, taskID platform.ID, scheduledFor int64) (*influxdb.Run, error) { defer s.ForceRunCalls.IncrFn()() return s.ForceRunFn(ctx, taskID, scheduledFor) } type TaskControlService struct { - CreateRunFn func(ctx context.Context, taskID influxdb.ID, scheduledFor time.Time, runAt time.Time) (*influxdb.Run, error) - CurrentlyRunningFn func(ctx context.Context, taskID influxdb.ID) ([]*influxdb.Run, error) - ManualRunsFn func(ctx context.Context, taskID influxdb.ID) ([]*influxdb.Run, error) - StartManualRunFn func(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) - FinishRunFn func(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) - UpdateRunStateFn func(ctx context.Context, taskID, runID influxdb.ID, when time.Time, state influxdb.RunStatus) error - AddRunLogFn func(ctx context.Context, taskID, runID influxdb.ID, when time.Time, log string) error + CreateRunFn func(ctx context.Context, taskID platform.ID, scheduledFor time.Time, runAt time.Time) (*influxdb.Run, error) + CurrentlyRunningFn func(ctx context.Context, taskID platform.ID) ([]*influxdb.Run, error) + ManualRunsFn func(ctx context.Context, taskID platform.ID) ([]*influxdb.Run, error) + StartManualRunFn func(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) + FinishRunFn func(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) + UpdateRunStateFn func(ctx context.Context, taskID, runID platform.ID, when time.Time, state influxdb.RunStatus) error + AddRunLogFn func(ctx context.Context, taskID, runID platform.ID, when time.Time, log string) error } -func (tcs *TaskControlService) CreateRun(ctx context.Context, taskID influxdb.ID, scheduledFor time.Time, runAt time.Time) (*influxdb.Run, error) { +func (tcs *TaskControlService) CreateRun(ctx context.Context, taskID platform.ID, scheduledFor time.Time, runAt time.Time) (*influxdb.Run, error) { return tcs.CreateRunFn(ctx, taskID, scheduledFor, runAt) } -func (tcs *TaskControlService) CurrentlyRunning(ctx context.Context, taskID influxdb.ID) ([]*influxdb.Run, error) { +func (tcs *TaskControlService) CurrentlyRunning(ctx context.Context, taskID platform.ID) ([]*influxdb.Run, error) { return tcs.CurrentlyRunningFn(ctx, taskID) } -func (tcs *TaskControlService) ManualRuns(ctx context.Context, taskID influxdb.ID) ([]*influxdb.Run, error) { +func (tcs *TaskControlService) ManualRuns(ctx context.Context, taskID platform.ID) ([]*influxdb.Run, error) { return tcs.ManualRunsFn(ctx, taskID) } -func (tcs *TaskControlService) StartManualRun(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (tcs *TaskControlService) StartManualRun(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { return tcs.StartManualRunFn(ctx, taskID, runID) } -func (tcs *TaskControlService) FinishRun(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (tcs *TaskControlService) FinishRun(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { return tcs.FinishRunFn(ctx, taskID, runID) } -func (tcs *TaskControlService) UpdateRunState(ctx context.Context, taskID, runID influxdb.ID, when time.Time, state influxdb.RunStatus) error { +func (tcs *TaskControlService) UpdateRunState(ctx context.Context, taskID, runID platform.ID, when time.Time, state influxdb.RunStatus) error { return tcs.UpdateRunStateFn(ctx, taskID, runID, when, state) } -func (tcs *TaskControlService) AddRunLog(ctx context.Context, taskID, runID influxdb.ID, when time.Time, log string) error { +func (tcs *TaskControlService) AddRunLog(ctx context.Context, taskID, runID platform.ID, when time.Time, log string) error { return tcs.AddRunLogFn(ctx, taskID, runID, when, log) } diff --git a/mock/telegraf_service.go b/mock/telegraf_service.go index a2b59d26143..2801e45520b 100644 --- a/mock/telegraf_service.go +++ b/mock/telegraf_service.go @@ -3,6 +3,8 @@ package mock import ( "context" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" ) @@ -11,15 +13,15 @@ var _ platform.TelegrafConfigStore = (*TelegrafConfigStore)(nil) // TelegrafConfigStore represents a service for managing telegraf config data. type TelegrafConfigStore struct { *UserResourceMappingService - FindTelegrafConfigByIDF func(ctx context.Context, id platform.ID) (*platform.TelegrafConfig, error) + FindTelegrafConfigByIDF func(ctx context.Context, id platform2.ID) (*platform.TelegrafConfig, error) FindTelegrafConfigByIDCalls SafeCount FindTelegrafConfigsF func(ctx context.Context, filter platform.TelegrafConfigFilter, opt ...platform.FindOptions) ([]*platform.TelegrafConfig, int, error) FindTelegrafConfigsCalls SafeCount - CreateTelegrafConfigF func(ctx context.Context, tc *platform.TelegrafConfig, userID platform.ID) error + CreateTelegrafConfigF func(ctx context.Context, tc *platform.TelegrafConfig, userID platform2.ID) error CreateTelegrafConfigCalls SafeCount - UpdateTelegrafConfigF func(ctx context.Context, id platform.ID, tc *platform.TelegrafConfig, userID platform.ID) (*platform.TelegrafConfig, error) + UpdateTelegrafConfigF func(ctx context.Context, id platform2.ID, tc *platform.TelegrafConfig, userID platform2.ID) (*platform.TelegrafConfig, error) UpdateTelegrafConfigCalls SafeCount - DeleteTelegrafConfigF func(ctx context.Context, id platform.ID) error + DeleteTelegrafConfigF func(ctx context.Context, id platform2.ID) error DeleteTelegrafConfigCalls SafeCount } @@ -27,26 +29,26 @@ type TelegrafConfigStore struct { func NewTelegrafConfigStore() *TelegrafConfigStore { return &TelegrafConfigStore{ UserResourceMappingService: NewUserResourceMappingService(), - FindTelegrafConfigByIDF: func(ctx context.Context, id platform.ID) (*platform.TelegrafConfig, error) { + FindTelegrafConfigByIDF: func(ctx context.Context, id platform2.ID) (*platform.TelegrafConfig, error) { return nil, nil }, FindTelegrafConfigsF: func(_ context.Context, f platform.TelegrafConfigFilter, opt ...platform.FindOptions) ([]*platform.TelegrafConfig, int, error) { return nil, 0, nil }, - CreateTelegrafConfigF: func(_ context.Context, tc *platform.TelegrafConfig, userID platform.ID) error { + CreateTelegrafConfigF: func(_ context.Context, tc *platform.TelegrafConfig, userID platform2.ID) error { return nil }, - UpdateTelegrafConfigF: func(_ context.Context, id platform.ID, tc *platform.TelegrafConfig, userID platform.ID) (*platform.TelegrafConfig, error) { + UpdateTelegrafConfigF: func(_ context.Context, id platform2.ID, tc *platform.TelegrafConfig, userID platform2.ID) (*platform.TelegrafConfig, error) { return nil, nil }, - DeleteTelegrafConfigF: func(_ context.Context, id platform.ID) error { + DeleteTelegrafConfigF: func(_ context.Context, id platform2.ID) error { return nil }, } } // FindTelegrafConfigByID returns a single telegraf config by ID. -func (s *TelegrafConfigStore) FindTelegrafConfigByID(ctx context.Context, id platform.ID) (*platform.TelegrafConfig, error) { +func (s *TelegrafConfigStore) FindTelegrafConfigByID(ctx context.Context, id platform2.ID) (*platform.TelegrafConfig, error) { defer s.FindTelegrafConfigByIDCalls.IncrFn()() return s.FindTelegrafConfigByIDF(ctx, id) } @@ -59,20 +61,20 @@ func (s *TelegrafConfigStore) FindTelegrafConfigs(ctx context.Context, filter pl } // CreateTelegrafConfig creates a new telegraf config and sets b.ID with the new identifier. -func (s *TelegrafConfigStore) CreateTelegrafConfig(ctx context.Context, tc *platform.TelegrafConfig, userID platform.ID) error { +func (s *TelegrafConfigStore) CreateTelegrafConfig(ctx context.Context, tc *platform.TelegrafConfig, userID platform2.ID) error { defer s.CreateTelegrafConfigCalls.IncrFn()() return s.CreateTelegrafConfigF(ctx, tc, userID) } // UpdateTelegrafConfig updates a single telegraf config. // Returns the new telegraf config after update. -func (s *TelegrafConfigStore) UpdateTelegrafConfig(ctx context.Context, id platform.ID, tc *platform.TelegrafConfig, userID platform.ID) (*platform.TelegrafConfig, error) { +func (s *TelegrafConfigStore) UpdateTelegrafConfig(ctx context.Context, id platform2.ID, tc *platform.TelegrafConfig, userID platform2.ID) (*platform.TelegrafConfig, error) { defer s.UpdateTelegrafConfigCalls.IncrFn()() return s.UpdateTelegrafConfigF(ctx, id, tc, userID) } // DeleteTelegrafConfig removes a telegraf config by ID. -func (s *TelegrafConfigStore) DeleteTelegrafConfig(ctx context.Context, id platform.ID) error { +func (s *TelegrafConfigStore) DeleteTelegrafConfig(ctx context.Context, id platform2.ID) error { defer s.DeleteTelegrafConfigCalls.IncrFn()() return s.DeleteTelegrafConfigF(ctx, id) } diff --git a/mock/user_resource_mapping_service.go b/mock/user_resource_mapping_service.go index 53c092e14dc..eea56274b65 100644 --- a/mock/user_resource_mapping_service.go +++ b/mock/user_resource_mapping_service.go @@ -3,6 +3,8 @@ package mock import ( "context" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" ) @@ -12,7 +14,7 @@ var _ platform.UserResourceMappingService = &UserResourceMappingService{} type UserResourceMappingService struct { FindMappingsFn func(context.Context, platform.UserResourceMappingFilter) ([]*platform.UserResourceMapping, int, error) CreateMappingFn func(context.Context, *platform.UserResourceMapping) error - DeleteMappingFn func(context.Context, platform.ID, platform.ID) error + DeleteMappingFn func(context.Context, platform2.ID, platform2.ID) error } // NewUserResourceMappingService returns a mock of UserResourceMappingService @@ -23,7 +25,7 @@ func NewUserResourceMappingService() *UserResourceMappingService { return nil, 0, nil }, CreateMappingFn: func(context.Context, *platform.UserResourceMapping) error { return nil }, - DeleteMappingFn: func(context.Context, platform.ID, platform.ID) error { return nil }, + DeleteMappingFn: func(context.Context, platform2.ID, platform2.ID) error { return nil }, } } @@ -38,6 +40,6 @@ func (s *UserResourceMappingService) CreateUserResourceMapping(ctx context.Conte } // DeleteUserResourceMapping removes a UserResourceMapping. -func (s *UserResourceMappingService) DeleteUserResourceMapping(ctx context.Context, resourceID platform.ID, userID platform.ID) error { +func (s *UserResourceMappingService) DeleteUserResourceMapping(ctx context.Context, resourceID platform2.ID, userID platform2.ID) error { return s.DeleteMappingFn(ctx, resourceID, userID) } diff --git a/mock/user_service.go b/mock/user_service.go index f6ba710923d..a3cc6da6c23 100644 --- a/mock/user_service.go +++ b/mock/user_service.go @@ -3,6 +3,8 @@ package mock import ( "context" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" ) @@ -12,32 +14,32 @@ var _ platform.UserService = (*UserService)(nil) // also makes it a suitable mock to use wherever an platform.UserService is required. type UserService struct { // Methods for a platform.UserService - FindUserByIDFn func(context.Context, platform.ID) (*platform.User, error) + FindUserByIDFn func(context.Context, platform2.ID) (*platform.User, error) FindUsersFn func(context.Context, platform.UserFilter, ...platform.FindOptions) ([]*platform.User, int, error) CreateUserFn func(context.Context, *platform.User) error - DeleteUserFn func(context.Context, platform.ID) error + DeleteUserFn func(context.Context, platform2.ID) error FindUserFn func(context.Context, platform.UserFilter) (*platform.User, error) - UpdateUserFn func(context.Context, platform.ID, platform.UserUpdate) (*platform.User, error) - FindPermissionForUserFn func(context.Context, platform.ID) (platform.PermissionSet, error) + UpdateUserFn func(context.Context, platform2.ID, platform.UserUpdate) (*platform.User, error) + FindPermissionForUserFn func(context.Context, platform2.ID) (platform.PermissionSet, error) } // NewUserService returns a mock of UserService where its methods will return zero values. func NewUserService() *UserService { return &UserService{ - FindUserByIDFn: func(context.Context, platform.ID) (*platform.User, error) { return nil, nil }, + FindUserByIDFn: func(context.Context, platform2.ID) (*platform.User, error) { return nil, nil }, FindUserFn: func(context.Context, platform.UserFilter) (*platform.User, error) { return nil, nil }, CreateUserFn: func(context.Context, *platform.User) error { return nil }, - UpdateUserFn: func(context.Context, platform.ID, platform.UserUpdate) (*platform.User, error) { return nil, nil }, - DeleteUserFn: func(context.Context, platform.ID) error { return nil }, + UpdateUserFn: func(context.Context, platform2.ID, platform.UserUpdate) (*platform.User, error) { return nil, nil }, + DeleteUserFn: func(context.Context, platform2.ID) error { return nil }, FindUsersFn: func(context.Context, platform.UserFilter, ...platform.FindOptions) ([]*platform.User, int, error) { return nil, 0, nil }, - FindPermissionForUserFn: func(context.Context, platform.ID) (platform.PermissionSet, error) { return nil, nil }, + FindPermissionForUserFn: func(context.Context, platform2.ID) (platform.PermissionSet, error) { return nil, nil }, } } // FindUserByID returns a single User by ID. -func (s *UserService) FindUserByID(ctx context.Context, id platform.ID) (*platform.User, error) { +func (s *UserService) FindUserByID(ctx context.Context, id platform2.ID) (*platform.User, error) { return s.FindUserByIDFn(ctx, id) } @@ -52,7 +54,7 @@ func (s *UserService) CreateUser(ctx context.Context, User *platform.User) error } // DeleteUser removes a User by ID. -func (s *UserService) DeleteUser(ctx context.Context, id platform.ID) error { +func (s *UserService) DeleteUser(ctx context.Context, id platform2.ID) error { return s.DeleteUserFn(ctx, id) } @@ -62,10 +64,10 @@ func (s *UserService) FindUser(ctx context.Context, filter platform.UserFilter) } // UpdateUser updates a user -func (s *UserService) UpdateUser(ctx context.Context, id platform.ID, upd platform.UserUpdate) (*platform.User, error) { +func (s *UserService) UpdateUser(ctx context.Context, id platform2.ID, upd platform.UserUpdate) (*platform.User, error) { return s.UpdateUserFn(ctx, id, upd) } -func (s *UserService) FindPermissionForUser(ctx context.Context, uid platform.ID) (platform.PermissionSet, error) { +func (s *UserService) FindPermissionForUser(ctx context.Context, uid platform2.ID) (platform.PermissionSet, error) { return s.FindPermissionForUserFn(ctx, uid) } diff --git a/mock/variable_service.go b/mock/variable_service.go index 8d40f1eca17..d584a3e8181 100644 --- a/mock/variable_service.go +++ b/mock/variable_service.go @@ -3,6 +3,8 @@ package mock import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -11,15 +13,15 @@ var _ influxdb.VariableService = &VariableService{} type VariableService struct { CreateVariableF func(context.Context, *influxdb.Variable) error CreateVariableCalls SafeCount - DeleteVariableF func(context.Context, influxdb.ID) error + DeleteVariableF func(context.Context, platform.ID) error DeleteVariableCalls SafeCount - FindVariableByIDF func(context.Context, influxdb.ID) (*influxdb.Variable, error) + FindVariableByIDF func(context.Context, platform.ID) (*influxdb.Variable, error) FindVariableByIDCalls SafeCount FindVariablesF func(context.Context, influxdb.VariableFilter, ...influxdb.FindOptions) ([]*influxdb.Variable, error) FindVariablesCalls SafeCount ReplaceVariableF func(context.Context, *influxdb.Variable) error ReplaceVariableCalls SafeCount - UpdateVariableF func(ctx context.Context, id influxdb.ID, update *influxdb.VariableUpdate) (*influxdb.Variable, error) + UpdateVariableF func(ctx context.Context, id platform.ID, update *influxdb.VariableUpdate) (*influxdb.Variable, error) UpdateVariableCalls SafeCount } @@ -27,13 +29,13 @@ type VariableService struct { func NewVariableService() *VariableService { return &VariableService{ CreateVariableF: func(context.Context, *influxdb.Variable) error { return nil }, - DeleteVariableF: func(context.Context, influxdb.ID) error { return nil }, - FindVariableByIDF: func(context.Context, influxdb.ID) (*influxdb.Variable, error) { return nil, nil }, + DeleteVariableF: func(context.Context, platform.ID) error { return nil }, + FindVariableByIDF: func(context.Context, platform.ID) (*influxdb.Variable, error) { return nil, nil }, FindVariablesF: func(context.Context, influxdb.VariableFilter, ...influxdb.FindOptions) ([]*influxdb.Variable, error) { return nil, nil }, ReplaceVariableF: func(context.Context, *influxdb.Variable) error { return nil }, - UpdateVariableF: func(ctx context.Context, id influxdb.ID, update *influxdb.VariableUpdate) (*influxdb.Variable, error) { + UpdateVariableF: func(ctx context.Context, id platform.ID, update *influxdb.VariableUpdate) (*influxdb.Variable, error) { return nil, nil }, } @@ -54,17 +56,17 @@ func (s *VariableService) FindVariables(ctx context.Context, filter influxdb.Var return s.FindVariablesF(ctx, filter, opts...) } -func (s *VariableService) FindVariableByID(ctx context.Context, id influxdb.ID) (*influxdb.Variable, error) { +func (s *VariableService) FindVariableByID(ctx context.Context, id platform.ID) (*influxdb.Variable, error) { defer s.FindVariableByIDCalls.IncrFn()() return s.FindVariableByIDF(ctx, id) } -func (s *VariableService) DeleteVariable(ctx context.Context, id influxdb.ID) error { +func (s *VariableService) DeleteVariable(ctx context.Context, id platform.ID) error { defer s.DeleteVariableCalls.IncrFn()() return s.DeleteVariableF(ctx, id) } -func (s *VariableService) UpdateVariable(ctx context.Context, id influxdb.ID, update *influxdb.VariableUpdate) (*influxdb.Variable, error) { +func (s *VariableService) UpdateVariable(ctx context.Context, id platform.ID, update *influxdb.VariableUpdate) (*influxdb.Variable, error) { defer s.UpdateVariableCalls.IncrFn()() return s.UpdateVariableF(ctx, id, update) } diff --git a/notification.go b/notification.go index a5a139c7879..3a15a5d9774 100644 --- a/notification.go +++ b/notification.go @@ -3,6 +3,9 @@ package influxdb import ( "context" "encoding/json" + + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) // NotificationRule is a *Query* of a *Status Bucket* that returns the *Status*. @@ -13,21 +16,21 @@ type NotificationRule interface { Type() string json.Marshaler CRUDLogSetter - SetID(id ID) - SetOrgID(id ID) + SetID(id platform.ID) + SetOrgID(id platform.ID) SetName(name string) SetDescription(description string) - GetID() ID + GetID() platform.ID GetCRUDLog() CRUDLog - GetOrgID() ID + GetOrgID() platform.ID GetName() string GetDescription() string - SetOwnerID(id ID) + SetOwnerID(id platform.ID) ClearPrivateData() - GetOwnerID() ID - SetTaskID(id ID) - GetTaskID() ID - GetEndpointID() ID + GetOwnerID() platform.ID + SetTaskID(id platform.ID) + GetTaskID() platform.ID + GetEndpointID() platform.ID GetLimit() *Limit GenerateFlux(NotificationEndpoint) (string, error) MatchesTags(tags []Tag) bool @@ -36,25 +39,25 @@ type NotificationRule interface { // NotificationRuleStore represents a service for managing notification rule. type NotificationRuleStore interface { // FindNotificationRuleByID returns a single notification rule by ID. - FindNotificationRuleByID(ctx context.Context, id ID) (NotificationRule, error) + FindNotificationRuleByID(ctx context.Context, id platform.ID) (NotificationRule, error) // FindNotificationRules returns a list of notification rules that match filter and the total count of matching notification rules. // Additional options provide pagination & sorting. FindNotificationRules(ctx context.Context, filter NotificationRuleFilter, opt ...FindOptions) ([]NotificationRule, int, error) // CreateNotificationRule creates a new notification rule and sets b.ID with the new identifier. - CreateNotificationRule(ctx context.Context, nr NotificationRuleCreate, userID ID) error + CreateNotificationRule(ctx context.Context, nr NotificationRuleCreate, userID platform.ID) error // UpdateNotificationRuleUpdateNotificationRule updates a single notification rule. // Returns the new notification rule after update. - UpdateNotificationRule(ctx context.Context, id ID, nr NotificationRuleCreate, userID ID) (NotificationRule, error) + UpdateNotificationRule(ctx context.Context, id platform.ID, nr NotificationRuleCreate, userID platform.ID) (NotificationRule, error) // PatchNotificationRule updates a single notification rule with changeset. // Returns the new notification rule state after update. - PatchNotificationRule(ctx context.Context, id ID, upd NotificationRuleUpdate) (NotificationRule, error) + PatchNotificationRule(ctx context.Context, id platform.ID, upd NotificationRuleUpdate) (NotificationRule, error) // DeleteNotificationRule removes a notification rule by ID. - DeleteNotificationRule(ctx context.Context, id ID) error + DeleteNotificationRule(ctx context.Context, id platform.ID) error } // Limit don't notify me more than times every seconds. @@ -67,7 +70,7 @@ type Limit struct { // NotificationRuleFilter represents a set of filter that restrict the returned notification rules. type NotificationRuleFilter struct { - OrgID *ID + OrgID *platform.ID Organization *string Tags []Tag UserResourceMappingFilter @@ -109,15 +112,15 @@ type NotificationRuleUpdate struct { // Valid will verify if the NotificationRuleUpdate is valid. func (n *NotificationRuleUpdate) Valid() error { if n.Name != nil && *n.Name == "" { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Notification Rule Name can't be empty", } } if n.Description != nil && *n.Description == "" { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Notification Rule Description can't be empty", } } diff --git a/notification/check/check.go b/notification/check/check.go index 7eabd1e758b..5cabe36b2cc 100644 --- a/notification/check/check.go +++ b/notification/check/check.go @@ -4,6 +4,9 @@ import ( "encoding/json" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/flux/ast" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/notification" @@ -12,15 +15,15 @@ import ( // Base will embed inside a check. type Base struct { - ID influxdb.ID `json:"id,omitempty"` + ID platform.ID `json:"id,omitempty"` Name string `json:"name"` Description string `json:"description,omitempty"` - OwnerID influxdb.ID `json:"ownerID,omitempty"` - OrgID influxdb.ID `json:"orgID,omitempty"` + OwnerID platform.ID `json:"ownerID,omitempty"` + OrgID platform.ID `json:"orgID,omitempty"` Query influxdb.DashboardQuery `json:"query"` // Care should be taken to prevent TaskID from being exposed publicly. - TaskID influxdb.ID `json:"taskID,omitempty"` + TaskID platform.ID `json:"taskID,omitempty"` // } todo: separate these // NonCustomCheckBase will embed inside non-custom checks. // type NonCustomCheckBase struct { @@ -38,50 +41,50 @@ type Base struct { // Valid returns err if the check is invalid. func (b Base) Valid(lang influxdb.FluxLanguageService) error { if !b.ID.Valid() { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Check ID is invalid", } } if b.Name == "" { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Check Name can't be empty", } } if !b.OwnerID.Valid() { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Check OwnerID is invalid", } } if !b.OrgID.Valid() { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Check OrgID is invalid", } } if b.Every == nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Check Every must exist", } } if len(b.Every.Values) == 0 { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Check Every can't be empty", } } if b.Offset != nil && len(b.Offset.Values) == 0 { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Check Offset can't be empty", } } if b.Offset != nil && b.Offset.TimeDuration() >= b.Every.TimeDuration() { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Offset should not be equal or greater than the interval", } } @@ -132,22 +135,22 @@ func (b Base) generateFluxASTCheckDefinition(checkType string) ast.Statement { } // GetID implements influxdb.Getter interface. -func (b Base) GetID() influxdb.ID { +func (b Base) GetID() platform.ID { return b.ID } // GetOrgID implements influxdb.Getter interface. -func (b Base) GetOrgID() influxdb.ID { +func (b Base) GetOrgID() platform.ID { return b.OrgID } // GetOwnerID gets the ownerID associated with a Base. -func (b Base) GetOwnerID() influxdb.ID { +func (b Base) GetOwnerID() platform.ID { return b.OwnerID } // GetTaskID retrieves the task ID for a check. -func (b Base) GetTaskID() influxdb.ID { +func (b Base) GetTaskID() platform.ID { return b.TaskID } @@ -167,12 +170,12 @@ func (b *Base) GetDescription() string { } // SetID will set the primary key. -func (b *Base) SetID(id influxdb.ID) { +func (b *Base) SetID(id platform.ID) { b.ID = id } // SetOrgID will set the org key. -func (b *Base) SetOrgID(id influxdb.ID) { +func (b *Base) SetOrgID(id platform.ID) { b.OrgID = id } @@ -182,12 +185,12 @@ func (b *Base) ClearPrivateData() { } // SetTaskID sets the taskID for a check. -func (b *Base) SetTaskID(id influxdb.ID) { +func (b *Base) SetTaskID(id platform.ID) { b.TaskID = id } // SetOwnerID sets the taskID for a check. -func (b *Base) SetOwnerID(id influxdb.ID) { +func (b *Base) SetOwnerID(id platform.ID) { b.OwnerID = id } @@ -213,14 +216,14 @@ func UnmarshalJSON(b []byte) (influxdb.Check, error) { Type string `json:"type"` } if err := json.Unmarshal(b, &raw); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unable to detect the check type from json", } } convertedFunc, ok := typeToCheck[raw.Type] if !ok { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Msg: fmt.Sprintf("invalid check type %s", raw.Type), } } diff --git a/notification/check/check_test.go b/notification/check/check_test.go index fb61325eb35..3c26ba0d43a 100644 --- a/notification/check/check_test.go +++ b/notification/check/check_test.go @@ -2,6 +2,7 @@ package check_test import ( "encoding/json" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "testing" "time" @@ -44,8 +45,8 @@ func TestValidCheck(t *testing.T) { { name: "invalid check id", src: &check.Deadman{}, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "Check ID is invalid", }, }, @@ -56,8 +57,8 @@ func TestValidCheck(t *testing.T) { ID: influxTesting.MustIDBase16(id1), }, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "Check Name can't be empty", }, }, @@ -69,8 +70,8 @@ func TestValidCheck(t *testing.T) { Name: "name1", }, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "Check OwnerID is invalid", }, }, @@ -83,8 +84,8 @@ func TestValidCheck(t *testing.T) { OwnerID: influxTesting.MustIDBase16(id2), }, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "Check OrgID is invalid", }, }, @@ -100,8 +101,8 @@ func TestValidCheck(t *testing.T) { Tags: []influxdb.Tag{{Key: "key1"}}, }, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "Check Every must exist", }, }, @@ -117,8 +118,8 @@ func TestValidCheck(t *testing.T) { Offset: mustDuration("2m"), }, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "Offset should not be equal or greater than the interval", }, }, @@ -135,8 +136,8 @@ func TestValidCheck(t *testing.T) { Tags: []influxdb.Tag{{Key: "key1"}}, }, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "tag must contain a key and a value", }, }, @@ -148,8 +149,8 @@ func TestValidCheck(t *testing.T) { &check.Range{Min: 200, Max: 100}, }, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "range threshold min can't be larger than max", }, }, diff --git a/notification/check/custom.go b/notification/check/custom.go index 5041e96dcac..8b929667814 100644 --- a/notification/check/custom.go +++ b/notification/check/custom.go @@ -4,6 +4,9 @@ import ( "encoding/json" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/flux/ast" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/notification/flux" @@ -14,13 +17,13 @@ var _ influxdb.Check = &Custom{} // Custom is the custom check. type Custom struct { - ID influxdb.ID `json:"id,omitempty"` + ID platform.ID `json:"id,omitempty"` Name string `json:"name"` Description string `json:"description,omitempty"` - OwnerID influxdb.ID `json:"ownerID,omitempty"` - OrgID influxdb.ID `json:"orgID,omitempty"` + OwnerID platform.ID `json:"ownerID,omitempty"` + OrgID platform.ID `json:"orgID,omitempty"` Query influxdb.DashboardQuery `json:"query"` - TaskID influxdb.ID `json:"taskID,omitempty"` + TaskID platform.ID `json:"taskID,omitempty"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` } @@ -140,32 +143,32 @@ func (c *Custom) hasRequiredTaskOptions(lang influxdb.FluxLanguageService) (err } }) if !hasOptionTask { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Custom flux missing task option statement", } } if !hasName { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Custom flux missing name parameter from task option statement", } } if hasName && !nameMatchesCheck { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Name parameter from task option statement must match check name", } } if !hasEvery { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Custom flux missing every parameter from task option statement", } } if !hasOffset { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Custom flux missing offset parameter from task option statement", } } @@ -199,20 +202,20 @@ func (c *Custom) hasRequiredCheckParameters(lang influxdb.FluxLanguageService) ( }) if !hasCheckObject { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Custom flux must have an object called 'check'", } } if !checkNameMatches { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "_check_name parameter on check object must match check name", } } if !checkTypeIsCustom { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "_type parameter on check object must be set to 'custom'", } } @@ -266,22 +269,22 @@ func (c *Custom) ClearPrivateData() { } // SetTaskID sets the taskID for a check. -func (c *Custom) SetTaskID(id influxdb.ID) { +func (c *Custom) SetTaskID(id platform.ID) { c.TaskID = id } // GetTaskID retrieves the task ID for a check. -func (c *Custom) GetTaskID() influxdb.ID { +func (c *Custom) GetTaskID() platform.ID { return c.TaskID } // GetOwnerID gets the ownerID associated with a Check. -func (c *Custom) GetOwnerID() influxdb.ID { +func (c *Custom) GetOwnerID() platform.ID { return c.OwnerID } // SetOwnerID sets the taskID for a check. -func (c *Custom) SetOwnerID(id influxdb.ID) { +func (c *Custom) SetOwnerID(id platform.ID) { c.OwnerID = id } @@ -296,12 +299,12 @@ func (c *Custom) SetUpdatedAt(now time.Time) { } // SetID sets the primary key for a check -func (c *Custom) SetID(id influxdb.ID) { +func (c *Custom) SetID(id platform.ID) { c.ID = id } // SetOrgID is SetOrgID -func (c *Custom) SetOrgID(id influxdb.ID) { +func (c *Custom) SetOrgID(id platform.ID) { c.OrgID = id } @@ -316,7 +319,7 @@ func (c *Custom) SetDescription(description string) { } // GetID is GetID -func (c *Custom) GetID() influxdb.ID { +func (c *Custom) GetID() platform.ID { return c.ID } @@ -326,7 +329,7 @@ func (c *Custom) GetCRUDLog() influxdb.CRUDLog { } // GetOrgID gets the orgID associated with the Check -func (c *Custom) GetOrgID() influxdb.ID { +func (c *Custom) GetOrgID() platform.ID { return c.OrgID } diff --git a/notification/check/threshold.go b/notification/check/threshold.go index c319db3b689..5d1f57146d1 100644 --- a/notification/check/threshold.go +++ b/notification/check/threshold.go @@ -5,6 +5,8 @@ import ( "fmt" "strings" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/flux/ast" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/notification" @@ -82,7 +84,7 @@ func (t *Threshold) UnmarshalJSON(b []byte) error { } t.Thresholds = append(t.Thresholds, td) default: - return &influxdb.Error{ + return &errors.Error{ Msg: fmt.Sprintf("invalid threshold type %s", tdRaw.Type), } } @@ -466,8 +468,8 @@ func (td Range) MarshalJSON() ([]byte, error) { // Valid overwrite the base threshold. func (td Range) Valid() error { if td.Min > td.Max { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "range threshold min can't be larger than max", } } diff --git a/notification/endpoint/endpoint.go b/notification/endpoint/endpoint.go index 05956ba247e..0ca21108884 100644 --- a/notification/endpoint/endpoint.go +++ b/notification/endpoint/endpoint.go @@ -4,6 +4,9 @@ import ( "encoding/json" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) @@ -28,23 +31,23 @@ func UnmarshalJSON(b []byte) (influxdb.NotificationEndpoint, error) { Type string `json:"type"` } if err := json.Unmarshal(b, &raw); err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Msg: "unable to detect the notification endpoint type from json", } } convertedFunc, ok := typeToEndpoint[raw.Type] if !ok { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("invalid notification endpoint type %s", raw.Type), } } converted := convertedFunc() if err := json.Unmarshal(b, converted); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInternal, + return nil, &errors.Error{ + Code: errors.EInternal, Err: err, } } @@ -53,17 +56,17 @@ func UnmarshalJSON(b []byte) (influxdb.NotificationEndpoint, error) { // Base is the embed struct of every notification endpoint. type Base struct { - ID *influxdb.ID `json:"id,omitempty"` + ID *platform.ID `json:"id,omitempty"` Name string `json:"name"` Description string `json:"description,omitempty"` - OrgID *influxdb.ID `json:"orgID,omitempty"` + OrgID *platform.ID `json:"orgID,omitempty"` Status influxdb.Status `json:"status"` influxdb.CRUDLog } func (b Base) idStr() string { if b.ID == nil { - return influxdb.ID(0).String() + return platform.ID(0).String() } return b.ID.String() } @@ -74,20 +77,20 @@ func (b Base) validID() bool { func (b Base) valid() error { if !b.validID() { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Notification Endpoint ID is invalid", } } if b.Name == "" { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Notification Endpoint Name can't be empty", } } if b.Status != influxdb.Active && b.Status != influxdb.Inactive { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "invalid status", } } @@ -95,7 +98,7 @@ func (b Base) valid() error { } // GetID implements influxdb.Getter interface. -func (b Base) GetID() influxdb.ID { +func (b Base) GetID() platform.ID { if b.ID == nil { return 0 } @@ -108,7 +111,7 @@ func (b *Base) GetName() string { } // GetOrgID implements influxdb.Getter interface. -func (b Base) GetOrgID() influxdb.ID { +func (b Base) GetOrgID() platform.ID { return getID(b.OrgID) } @@ -128,12 +131,12 @@ func (b *Base) GetStatus() influxdb.Status { } // SetID will set the primary key. -func (b *Base) SetID(id influxdb.ID) { +func (b *Base) SetID(id platform.ID) { b.ID = &id } // SetOrgID will set the org key. -func (b *Base) SetOrgID(id influxdb.ID) { +func (b *Base) SetOrgID(id platform.ID) { b.OrgID = &id } @@ -152,7 +155,7 @@ func (b *Base) SetStatus(status influxdb.Status) { b.Status = status } -func getID(id *influxdb.ID) influxdb.ID { +func getID(id *platform.ID) platform.ID { if id == nil { return 0 } diff --git a/notification/endpoint/endpoint_test.go b/notification/endpoint/endpoint_test.go index ea94df19e53..32c172a7f14 100644 --- a/notification/endpoint/endpoint_test.go +++ b/notification/endpoint/endpoint_test.go @@ -3,6 +3,7 @@ package endpoint_test import ( "encoding/json" "fmt" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" "net/http" "net/url" "testing" @@ -42,8 +43,8 @@ func TestValidEndpoint(t *testing.T) { { name: "invalid endpoint id", src: &endpoint.Slack{}, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors2.Error{ + Code: errors2.EInvalid, Msg: "Notification Endpoint ID is invalid", }, }, @@ -56,8 +57,8 @@ func TestValidEndpoint(t *testing.T) { OrgID: id3, }, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors2.Error{ + Code: errors2.EInvalid, Msg: "invalid status", }, }, @@ -72,8 +73,8 @@ func TestValidEndpoint(t *testing.T) { ClientURL: "https://events.pagerduty.com/v2/enqueue", RoutingKey: influxdb.SecretField{Key: id1.String() + "-routing-key"}, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors2.Error{ + Code: errors2.EInvalid, Msg: "Notification Endpoint Name can't be empty", }, }, @@ -88,8 +89,8 @@ func TestValidEndpoint(t *testing.T) { Token: influxdb.SecretField{Key: id1.String() + "-token"}, Channel: "-1001406363649", }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors2.Error{ + Code: errors2.EInvalid, Msg: "Notification Endpoint Name can't be empty", }, }, @@ -98,8 +99,8 @@ func TestValidEndpoint(t *testing.T) { src: &endpoint.Slack{ Base: goodBase, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors2.Error{ + Code: errors2.EInvalid, Msg: "slack endpoint URL must be provided", }, }, @@ -115,8 +116,8 @@ func TestValidEndpoint(t *testing.T) { URL: "posts://er:{DEf1=ghi@:5432/db?ssl", Err: errors.New("net/url: invalid userinfo"), } - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors2.Error{ + Code: errors2.EInvalid, Msg: fmt.Sprintf("slack endpoint URL is invalid: %s", err.Error()), } }, @@ -135,8 +136,8 @@ func TestValidEndpoint(t *testing.T) { Base: goodBase, URL: "localhost", }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors2.Error{ + Code: errors2.EInvalid, Msg: "invalid http http method", }, }, @@ -148,8 +149,8 @@ func TestValidEndpoint(t *testing.T) { Method: "GET", AuthMethod: "bearer", }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors2.Error{ + Code: errors2.EInvalid, Msg: "invalid http token for bearer auth", }, }, @@ -161,8 +162,8 @@ func TestValidEndpoint(t *testing.T) { Method: http.MethodGet, AuthMethod: "basic", }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors2.Error{ + Code: errors2.EInvalid, Msg: "invalid http username/password for basic auth", }, }, @@ -171,8 +172,8 @@ func TestValidEndpoint(t *testing.T) { src: &endpoint.Telegram{ Base: goodBase, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors2.Error{ + Code: errors2.EInvalid, Msg: "empty telegram bot token", }, }, @@ -182,8 +183,8 @@ func TestValidEndpoint(t *testing.T) { Base: goodBase, Token: influxdb.SecretField{Key: id1.String() + "-token"}, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors2.Error{ + Code: errors2.EInvalid, Msg: "empty telegram channel", }, }, diff --git a/notification/endpoint/http.go b/notification/endpoint/http.go index 4a3fd81c4b9..3929afeaee5 100644 --- a/notification/endpoint/http.go +++ b/notification/endpoint/http.go @@ -7,6 +7,8 @@ import ( "net/http" "net/url" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) @@ -80,38 +82,38 @@ func (s HTTP) Valid() error { return err } if s.URL == "" { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "http endpoint URL is empty", } } if _, err := url.Parse(s.URL); err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("http endpoint URL is invalid: %s", err.Error()), } } if !goodHTTPMethod[s.Method] { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "invalid http http method", } } if !goodHTTPAuthMethod[s.AuthMethod] { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "invalid http auth method", } } if s.AuthMethod == "basic" && (s.Username.Key == "" || s.Password.Key == "") { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "invalid http username/password for basic auth", } } if s.AuthMethod == "bearer" && s.Token.Key == "" { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "invalid http token for bearer auth", } } @@ -144,7 +146,7 @@ func (s HTTP) ParseResponse(resp *http.Response) error { if err != nil { return err } - return &influxdb.Error{ + return &errors.Error{ Msg: string(body), } } diff --git a/notification/endpoint/pagerduty.go b/notification/endpoint/pagerduty.go index 57cc7b4fcab..7ec2299088f 100644 --- a/notification/endpoint/pagerduty.go +++ b/notification/endpoint/pagerduty.go @@ -3,6 +3,8 @@ package endpoint import ( "encoding/json" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) @@ -41,8 +43,8 @@ func (s PagerDuty) Valid() error { return err } if s.RoutingKey.Key == "" { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "pagerduty routing key is invalid", } } diff --git a/notification/endpoint/service/service.go b/notification/endpoint/service/service.go index 418805f6845..ad7edc32992 100644 --- a/notification/endpoint/service/service.go +++ b/notification/endpoint/service/service.go @@ -3,6 +3,8 @@ package service import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + influxdb "github.com/influxdata/influxdb/v2" ) @@ -23,7 +25,7 @@ func New(store influxdb.NotificationEndpointService, secretSVC influxdb.SecretSe var _ influxdb.NotificationEndpointService = (*Service)(nil) // FindNotificationEndpointByID returns a single notification endpoint by ID. -func (s *Service) FindNotificationEndpointByID(ctx context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { +func (s *Service) FindNotificationEndpointByID(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { return s.endpointStore.FindNotificationEndpointByID(ctx, id) } @@ -34,7 +36,7 @@ func (s *Service) FindNotificationEndpoints(ctx context.Context, filter influxdb } // CreateNotificationEndpoint creates a new notification endpoint and sets b.ID with the new identifier. -func (s *Service) CreateNotificationEndpoint(ctx context.Context, edp influxdb.NotificationEndpoint, userID influxdb.ID) error { +func (s *Service) CreateNotificationEndpoint(ctx context.Context, edp influxdb.NotificationEndpoint, userID platform.ID) error { err := s.endpointStore.CreateNotificationEndpoint(ctx, edp, userID) if err != nil { return err @@ -55,7 +57,7 @@ func (s *Service) CreateNotificationEndpoint(ctx context.Context, edp influxdb.N // UpdateNotificationEndpoint updates a single notification endpoint. // Returns the new notification endpoint after update. -func (s *Service) UpdateNotificationEndpoint(ctx context.Context, id influxdb.ID, nr influxdb.NotificationEndpoint, userID influxdb.ID) (influxdb.NotificationEndpoint, error) { +func (s *Service) UpdateNotificationEndpoint(ctx context.Context, id platform.ID, nr influxdb.NotificationEndpoint, userID platform.ID) (influxdb.NotificationEndpoint, error) { nr.BackfillSecretKeys() // :sadpanda: updatedEndpoint, err := s.endpointStore.UpdateNotificationEndpoint(ctx, id, nr, userID) if err != nil { @@ -82,11 +84,11 @@ func (s *Service) UpdateNotificationEndpoint(ctx context.Context, id influxdb.ID // PatchNotificationEndpoint updates a single notification endpoint with changeset. // Returns the new notification endpoint state after update. -func (s *Service) PatchNotificationEndpoint(ctx context.Context, id influxdb.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { +func (s *Service) PatchNotificationEndpoint(ctx context.Context, id platform.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { return s.endpointStore.PatchNotificationEndpoint(ctx, id, upd) } // DeleteNotificationEndpoint removes a notification endpoint by ID, returns secret fields, orgID for further deletion. -func (s *Service) DeleteNotificationEndpoint(ctx context.Context, id influxdb.ID) ([]influxdb.SecretField, influxdb.ID, error) { +func (s *Service) DeleteNotificationEndpoint(ctx context.Context, id platform.ID) ([]influxdb.SecretField, platform.ID, error) { return s.endpointStore.DeleteNotificationEndpoint(ctx, id) } diff --git a/notification/endpoint/service/store.go b/notification/endpoint/service/store.go index bc2da6c31be..938b1986dba 100644 --- a/notification/endpoint/service/store.go +++ b/notification/endpoint/service/store.go @@ -3,6 +3,9 @@ package service import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + influxdb "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" "github.com/influxdata/influxdb/v2/notification/endpoint" @@ -11,9 +14,9 @@ import ( var ( // ErrNotificationEndpointNotFound is used when the notification endpoint is not found. - ErrNotificationEndpointNotFound = &influxdb.Error{ + ErrNotificationEndpointNotFound = &errors.Error{ Msg: "notification endpoint not found", - Code: influxdb.ENotFound, + Code: errors.ENotFound, } notificationEndpointBucket = []byte("notificationEndpointv1") @@ -54,7 +57,7 @@ type Store struct { endpointStore *kv.IndexStore - IDGenerator influxdb.IDGenerator + IDGenerator platform.IDGenerator TimeGenerator influxdb.TimeGenerator } @@ -68,13 +71,13 @@ func NewStore(store kv.Store) *Store { } // CreateNotificationEndpoint creates a new notification endpoint and sets b.ID with the new identifier. -func (s *Store) CreateNotificationEndpoint(ctx context.Context, edp influxdb.NotificationEndpoint, userID influxdb.ID) error { +func (s *Store) CreateNotificationEndpoint(ctx context.Context, edp influxdb.NotificationEndpoint, userID platform.ID) error { return s.kv.Update(ctx, func(tx kv.Tx) error { return s.createNotificationEndpoint(ctx, tx, edp, userID) }) } -func (s *Store) createNotificationEndpoint(ctx context.Context, tx kv.Tx, edp influxdb.NotificationEndpoint, userID influxdb.ID) error { +func (s *Store) createNotificationEndpoint(ctx context.Context, tx kv.Tx, edp influxdb.NotificationEndpoint, userID platform.ID) error { id := s.IDGenerator.ID() edp.SetID(id) now := s.TimeGenerator.Now() @@ -100,7 +103,7 @@ func (s *Store) createNotificationEndpoint(ctx context.Context, tx kv.Tx, edp in // UpdateNotificationEndpoint updates a single notification endpoint. // Returns the new notification endpoint after update. -func (s *Store) UpdateNotificationEndpoint(ctx context.Context, id influxdb.ID, edp influxdb.NotificationEndpoint, userID influxdb.ID) (influxdb.NotificationEndpoint, error) { +func (s *Store) UpdateNotificationEndpoint(ctx context.Context, id platform.ID, edp influxdb.NotificationEndpoint, userID platform.ID) (influxdb.NotificationEndpoint, error) { var err error err = s.kv.Update(ctx, func(tx kv.Tx) error { edp, err = s.updateNotificationEndpoint(ctx, tx, id, edp, userID) @@ -109,7 +112,7 @@ func (s *Store) UpdateNotificationEndpoint(ctx context.Context, id influxdb.ID, return edp, err } -func (s *Store) updateNotificationEndpoint(ctx context.Context, tx kv.Tx, id influxdb.ID, edp influxdb.NotificationEndpoint, userID influxdb.ID) (influxdb.NotificationEndpoint, error) { +func (s *Store) updateNotificationEndpoint(ctx context.Context, tx kv.Tx, id platform.ID, edp influxdb.NotificationEndpoint, userID platform.ID) (influxdb.NotificationEndpoint, error) { current, err := s.findNotificationEndpointByID(ctx, tx, id) if err != nil { return nil, err @@ -137,7 +140,7 @@ func (s *Store) updateNotificationEndpoint(ctx context.Context, tx kv.Tx, id inf // PatchNotificationEndpoint updates a single notification endpoint with changeset. // Returns the new notification endpoint state after update. -func (s *Store) PatchNotificationEndpoint(ctx context.Context, id influxdb.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { +func (s *Store) PatchNotificationEndpoint(ctx context.Context, id platform.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { var edp influxdb.NotificationEndpoint if err := s.kv.Update(ctx, func(tx kv.Tx) (err error) { edp, err = s.patchNotificationEndpoint(ctx, tx, id, upd) @@ -152,7 +155,7 @@ func (s *Store) PatchNotificationEndpoint(ctx context.Context, id influxdb.ID, u return edp, nil } -func (s *Store) patchNotificationEndpoint(ctx context.Context, tx kv.Tx, id influxdb.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { +func (s *Store) patchNotificationEndpoint(ctx context.Context, tx kv.Tx, id platform.ID, upd influxdb.NotificationEndpointUpdate) (influxdb.NotificationEndpoint, error) { edp, err := s.findNotificationEndpointByID(ctx, tx, id) if err != nil { return nil, err @@ -206,7 +209,7 @@ func (s *Store) PutNotificationEndpoint(ctx context.Context, edp influxdb.Notifi } // FindNotificationEndpointByID returns a single notification endpoint by ID. -func (s *Store) FindNotificationEndpointByID(ctx context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { +func (s *Store) FindNotificationEndpointByID(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { var ( edp influxdb.NotificationEndpoint err error @@ -220,7 +223,7 @@ func (s *Store) FindNotificationEndpointByID(ctx context.Context, id influxdb.ID return edp, err } -func (s *Store) findNotificationEndpointByID(ctx context.Context, tx kv.Tx, id influxdb.ID) (influxdb.NotificationEndpoint, error) { +func (s *Store) findNotificationEndpointByID(ctx context.Context, tx kv.Tx, id platform.ID) (influxdb.NotificationEndpoint, error) { decodedEnt, err := s.endpointStore.FindEnt(ctx, tx, kv.Entity{PK: kv.EncID(id)}) if err != nil { return nil, err @@ -283,7 +286,7 @@ func filterEndpointsFn(filter influxdb.NotificationEndpointFilter) func([]byte, } // DeleteNotificationEndpoint removes a notification endpoint by ID. -func (s *Store) DeleteNotificationEndpoint(ctx context.Context, id influxdb.ID) (flds []influxdb.SecretField, orgID influxdb.ID, err error) { +func (s *Store) DeleteNotificationEndpoint(ctx context.Context, id platform.ID) (flds []influxdb.SecretField, orgID platform.ID, err error) { err = s.kv.Update(ctx, func(tx kv.Tx) error { flds, orgID, err = s.deleteNotificationEndpoint(ctx, tx, id) return err @@ -291,7 +294,7 @@ func (s *Store) DeleteNotificationEndpoint(ctx context.Context, id influxdb.ID) return flds, orgID, err } -func (s *Store) deleteNotificationEndpoint(ctx context.Context, tx kv.Tx, id influxdb.ID) (flds []influxdb.SecretField, orgID influxdb.ID, err error) { +func (s *Store) deleteNotificationEndpoint(ctx context.Context, tx kv.Tx, id platform.ID) (flds []influxdb.SecretField, orgID platform.ID, err error) { edp, err := s.findNotificationEndpointByID(ctx, tx, id) if err != nil { return nil, 0, err diff --git a/notification/endpoint/service/testing/service.go b/notification/endpoint/service/testing/service.go index fdc6d9448c3..7f67d1f6ced 100644 --- a/notification/endpoint/service/testing/service.go +++ b/notification/endpoint/service/testing/service.go @@ -9,6 +9,9 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" influxdb "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" @@ -18,7 +21,7 @@ import ( ) const ( - oneID = influxdb.ID(iota + 1) + oneID = platform.ID(iota + 1) twoID threeID fourID @@ -35,7 +38,7 @@ var ( // NotificationEndpointFields includes prepopulated data for mapping tests. type NotificationEndpointFields struct { - IDGenerator influxdb.IDGenerator + IDGenerator platform.IDGenerator TimeGenerator influxdb.TimeGenerator NotificationEndpoints []influxdb.NotificationEndpoint Orgs []*influxdb.Organization @@ -101,7 +104,7 @@ func CreateNotificationEndpoint( ) { type args struct { notificationEndpoint influxdb.NotificationEndpoint - userID influxdb.ID + userID platform.ID } type wants struct { err error @@ -198,10 +201,10 @@ func FindNotificationEndpointByID( t *testing.T, ) { type args struct { - id influxdb.ID + id platform.ID } type wants struct { - err *influxdb.Error + err *errors.Error notificationEndpoint influxdb.NotificationEndpoint } @@ -250,11 +253,11 @@ func FindNotificationEndpointByID( }, }, args: args{ - id: influxdb.ID(0), + id: platform.ID(0), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "no key was provided for notification endpoint", }, }, @@ -297,8 +300,8 @@ func FindNotificationEndpointByID( id: threeID, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "notification endpoint not found", }, }, @@ -985,15 +988,15 @@ func UpdateNotificationEndpoint( t *testing.T, ) { type args struct { - userID influxdb.ID - orgID influxdb.ID - id influxdb.ID + userID platform.ID + orgID platform.ID + id platform.ID notificationEndpoint influxdb.NotificationEndpoint } type wants struct { notificationEndpoint influxdb.NotificationEndpoint - err *influxdb.Error + err *errors.Error } tests := []struct { name string @@ -1051,8 +1054,8 @@ func UpdateNotificationEndpoint( }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: `notification endpoint not found for key "0000000000000004"`, }, }, @@ -1225,13 +1228,13 @@ func PatchNotificationEndpoint( type args struct { //userID influxdb.ID - id influxdb.ID + id platform.ID upd influxdb.NotificationEndpointUpdate } type wants struct { notificationEndpoint influxdb.NotificationEndpoint - err *influxdb.Error + err *errors.Error } tests := []struct { name string @@ -1282,8 +1285,8 @@ func PatchNotificationEndpoint( }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "notification endpoint not found", }, }, @@ -1359,7 +1362,7 @@ func PatchNotificationEndpoint( if tt.wants.err == nil { require.NoError(t, err) } - iErr, ok := err.(*influxdb.Error) + iErr, ok := err.(*errors.Error) require.True(t, ok, err) assert.Equal(t, tt.wants.err.Code, iErr.Code) return @@ -1377,16 +1380,16 @@ func DeleteNotificationEndpoint( t *testing.T, ) { type args struct { - id influxdb.ID - orgID influxdb.ID - userID influxdb.ID + id platform.ID + orgID platform.ID + userID platform.ID } type wants struct { notificationEndpoints []influxdb.NotificationEndpoint secretFlds []influxdb.SecretField - orgID influxdb.ID - err *influxdb.Error + orgID platform.ID + err *errors.Error } tests := []struct { name string @@ -1429,13 +1432,13 @@ func DeleteNotificationEndpoint( }, }, args: args{ - id: influxdb.ID(0), + id: platform.ID(0), orgID: fourID, userID: sixID, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "no key was provided for notification endpoint", }, notificationEndpoints: []influxdb.NotificationEndpoint{ @@ -1508,8 +1511,8 @@ func DeleteNotificationEndpoint( userID: sixID, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "notification endpoint not found", }, notificationEndpoints: []influxdb.NotificationEndpoint{ @@ -1655,7 +1658,7 @@ func DeleteNotificationEndpoint( } } -func influxErrsEqual(t *testing.T, expected *influxdb.Error, actual error) { +func influxErrsEqual(t *testing.T, expected *errors.Error, actual error) { t.Helper() if expected != nil { @@ -1670,13 +1673,13 @@ func influxErrsEqual(t *testing.T, expected *influxdb.Error, actual error) { require.NoError(t, actual) return } - iErr, ok := actual.(*influxdb.Error) + iErr, ok := actual.(*errors.Error) require.True(t, ok) assert.Equal(t, expected.Code, iErr.Code) assert.Truef(t, strings.HasPrefix(iErr.Error(), expected.Error()), "expected: %s got err: %s", expected.Error(), actual.Error()) } -func idPtr(id influxdb.ID) *influxdb.ID { +func idPtr(id platform.ID) *platform.ID { return &id } @@ -1697,13 +1700,13 @@ func ErrorsEqual(t *testing.T, actual, expected error) { t.Errorf("expected error %s but received nil", expected.Error()) } - if influxdb.ErrorCode(expected) != influxdb.ErrorCode(actual) { + if errors.ErrorCode(expected) != errors.ErrorCode(actual) { t.Logf("\nexpected: %v\nactual: %v\n\n", expected, actual) - t.Errorf("expected error code %q but received %q", influxdb.ErrorCode(expected), influxdb.ErrorCode(actual)) + t.Errorf("expected error code %q but received %q", errors.ErrorCode(expected), errors.ErrorCode(actual)) } - if influxdb.ErrorMessage(expected) != influxdb.ErrorMessage(actual) { + if errors.ErrorMessage(expected) != errors.ErrorMessage(actual) { t.Logf("\nexpected: %v\nactual: %v\n\n", expected, actual) - t.Errorf("expected error message %q but received %q", influxdb.ErrorMessage(expected), influxdb.ErrorMessage(actual)) + t.Errorf("expected error message %q but received %q", errors.ErrorMessage(expected), errors.ErrorMessage(actual)) } } diff --git a/notification/endpoint/slack.go b/notification/endpoint/slack.go index c900acdcf1e..3e5f1cff80a 100644 --- a/notification/endpoint/slack.go +++ b/notification/endpoint/slack.go @@ -5,6 +5,8 @@ import ( "fmt" "net/url" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) @@ -46,15 +48,15 @@ func (s Slack) Valid() error { return err } if s.URL == "" { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "slack endpoint URL must be provided", } } if s.URL != "" { if _, err := url.Parse(s.URL); err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("slack endpoint URL is invalid: %s", err.Error()), } } diff --git a/notification/endpoint/telegram.go b/notification/endpoint/telegram.go index 00498ead39d..595bf9d2b00 100644 --- a/notification/endpoint/telegram.go +++ b/notification/endpoint/telegram.go @@ -3,6 +3,8 @@ package endpoint import ( "encoding/json" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) @@ -42,14 +44,14 @@ func (s Telegram) Valid() error { return err } if s.Token.Key == "" { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "empty telegram bot token", } } if s.Channel == "" { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "empty telegram channel", } } diff --git a/notification/endpoint/testing/service.go b/notification/endpoint/testing/service.go index fdc6d9448c3..7f67d1f6ced 100644 --- a/notification/endpoint/testing/service.go +++ b/notification/endpoint/testing/service.go @@ -9,6 +9,9 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" influxdb "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" @@ -18,7 +21,7 @@ import ( ) const ( - oneID = influxdb.ID(iota + 1) + oneID = platform.ID(iota + 1) twoID threeID fourID @@ -35,7 +38,7 @@ var ( // NotificationEndpointFields includes prepopulated data for mapping tests. type NotificationEndpointFields struct { - IDGenerator influxdb.IDGenerator + IDGenerator platform.IDGenerator TimeGenerator influxdb.TimeGenerator NotificationEndpoints []influxdb.NotificationEndpoint Orgs []*influxdb.Organization @@ -101,7 +104,7 @@ func CreateNotificationEndpoint( ) { type args struct { notificationEndpoint influxdb.NotificationEndpoint - userID influxdb.ID + userID platform.ID } type wants struct { err error @@ -198,10 +201,10 @@ func FindNotificationEndpointByID( t *testing.T, ) { type args struct { - id influxdb.ID + id platform.ID } type wants struct { - err *influxdb.Error + err *errors.Error notificationEndpoint influxdb.NotificationEndpoint } @@ -250,11 +253,11 @@ func FindNotificationEndpointByID( }, }, args: args{ - id: influxdb.ID(0), + id: platform.ID(0), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "no key was provided for notification endpoint", }, }, @@ -297,8 +300,8 @@ func FindNotificationEndpointByID( id: threeID, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "notification endpoint not found", }, }, @@ -985,15 +988,15 @@ func UpdateNotificationEndpoint( t *testing.T, ) { type args struct { - userID influxdb.ID - orgID influxdb.ID - id influxdb.ID + userID platform.ID + orgID platform.ID + id platform.ID notificationEndpoint influxdb.NotificationEndpoint } type wants struct { notificationEndpoint influxdb.NotificationEndpoint - err *influxdb.Error + err *errors.Error } tests := []struct { name string @@ -1051,8 +1054,8 @@ func UpdateNotificationEndpoint( }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: `notification endpoint not found for key "0000000000000004"`, }, }, @@ -1225,13 +1228,13 @@ func PatchNotificationEndpoint( type args struct { //userID influxdb.ID - id influxdb.ID + id platform.ID upd influxdb.NotificationEndpointUpdate } type wants struct { notificationEndpoint influxdb.NotificationEndpoint - err *influxdb.Error + err *errors.Error } tests := []struct { name string @@ -1282,8 +1285,8 @@ func PatchNotificationEndpoint( }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "notification endpoint not found", }, }, @@ -1359,7 +1362,7 @@ func PatchNotificationEndpoint( if tt.wants.err == nil { require.NoError(t, err) } - iErr, ok := err.(*influxdb.Error) + iErr, ok := err.(*errors.Error) require.True(t, ok, err) assert.Equal(t, tt.wants.err.Code, iErr.Code) return @@ -1377,16 +1380,16 @@ func DeleteNotificationEndpoint( t *testing.T, ) { type args struct { - id influxdb.ID - orgID influxdb.ID - userID influxdb.ID + id platform.ID + orgID platform.ID + userID platform.ID } type wants struct { notificationEndpoints []influxdb.NotificationEndpoint secretFlds []influxdb.SecretField - orgID influxdb.ID - err *influxdb.Error + orgID platform.ID + err *errors.Error } tests := []struct { name string @@ -1429,13 +1432,13 @@ func DeleteNotificationEndpoint( }, }, args: args{ - id: influxdb.ID(0), + id: platform.ID(0), orgID: fourID, userID: sixID, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "no key was provided for notification endpoint", }, notificationEndpoints: []influxdb.NotificationEndpoint{ @@ -1508,8 +1511,8 @@ func DeleteNotificationEndpoint( userID: sixID, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "notification endpoint not found", }, notificationEndpoints: []influxdb.NotificationEndpoint{ @@ -1655,7 +1658,7 @@ func DeleteNotificationEndpoint( } } -func influxErrsEqual(t *testing.T, expected *influxdb.Error, actual error) { +func influxErrsEqual(t *testing.T, expected *errors.Error, actual error) { t.Helper() if expected != nil { @@ -1670,13 +1673,13 @@ func influxErrsEqual(t *testing.T, expected *influxdb.Error, actual error) { require.NoError(t, actual) return } - iErr, ok := actual.(*influxdb.Error) + iErr, ok := actual.(*errors.Error) require.True(t, ok) assert.Equal(t, expected.Code, iErr.Code) assert.Truef(t, strings.HasPrefix(iErr.Error(), expected.Error()), "expected: %s got err: %s", expected.Error(), actual.Error()) } -func idPtr(id influxdb.ID) *influxdb.ID { +func idPtr(id platform.ID) *platform.ID { return &id } @@ -1697,13 +1700,13 @@ func ErrorsEqual(t *testing.T, actual, expected error) { t.Errorf("expected error %s but received nil", expected.Error()) } - if influxdb.ErrorCode(expected) != influxdb.ErrorCode(actual) { + if errors.ErrorCode(expected) != errors.ErrorCode(actual) { t.Logf("\nexpected: %v\nactual: %v\n\n", expected, actual) - t.Errorf("expected error code %q but received %q", influxdb.ErrorCode(expected), influxdb.ErrorCode(actual)) + t.Errorf("expected error code %q but received %q", errors.ErrorCode(expected), errors.ErrorCode(actual)) } - if influxdb.ErrorMessage(expected) != influxdb.ErrorMessage(actual) { + if errors.ErrorMessage(expected) != errors.ErrorMessage(actual) { t.Logf("\nexpected: %v\nactual: %v\n\n", expected, actual) - t.Errorf("expected error message %q but received %q", influxdb.ErrorMessage(expected), influxdb.ErrorMessage(actual)) + t.Errorf("expected error message %q but received %q", errors.ErrorMessage(expected), errors.ErrorMessage(actual)) } } diff --git a/notification/rule/http_test.go b/notification/rule/http_test.go index 5607ba524b3..f4e86974998 100644 --- a/notification/rule/http_test.go +++ b/notification/rule/http_test.go @@ -1,6 +1,7 @@ package rule_test import ( + "github.com/influxdata/influxdb/v2/kit/platform" "testing" "github.com/influxdata/influxdb/v2" @@ -58,7 +59,7 @@ all_statuses }, } - id := influxdb.ID(2) + id := platform.ID(2) e := &endpoint.HTTP{ Base: endpoint.Base{ ID: &id, @@ -126,7 +127,7 @@ all_statuses }, } - id := influxdb.ID(2) + id := platform.ID(2) e := &endpoint.HTTP{ Base: endpoint.Base{ ID: &id, @@ -202,7 +203,7 @@ all_statuses }, } - id := influxdb.ID(2) + id := platform.ID(2) e := &endpoint.HTTP{ Base: endpoint.Base{ ID: &id, @@ -275,7 +276,7 @@ all_statuses }, } - id := influxdb.ID(2) + id := platform.ID(2) e := &endpoint.HTTP{ Base: endpoint.Base{ ID: &id, diff --git a/notification/rule/pagerduty.go b/notification/rule/pagerduty.go index e787bb5a04f..166acf18064 100644 --- a/notification/rule/pagerduty.go +++ b/notification/rule/pagerduty.go @@ -4,6 +4,8 @@ import ( "encoding/json" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/flux/ast" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/notification/endpoint" @@ -36,8 +38,8 @@ func (s PagerDuty) Valid() error { return err } if s.MessageTemplate == "" { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "pagerduty invalid message template", } } diff --git a/notification/rule/rule.go b/notification/rule/rule.go index 7482f3f07a8..38082f61506 100644 --- a/notification/rule/rule.go +++ b/notification/rule/rule.go @@ -6,6 +6,9 @@ import ( "strings" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/flux/ast" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/notification" @@ -25,13 +28,13 @@ func UnmarshalJSON(b []byte) (influxdb.NotificationRule, error) { Typ string `json:"type"` } if err := json.Unmarshal(b, &raw); err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Msg: "unable to detect the notification type from json", } } convertedFunc, ok := typeToRule[raw.Typ] if !ok { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Msg: fmt.Sprintf("invalid notification type %s", raw.Typ), } } @@ -42,13 +45,13 @@ func UnmarshalJSON(b []byte) (influxdb.NotificationRule, error) { // Base is the embed struct of every notification rule. type Base struct { - ID influxdb.ID `json:"id,omitempty"` + ID platform.ID `json:"id,omitempty"` Name string `json:"name"` Description string `json:"description,omitempty"` - EndpointID influxdb.ID `json:"endpointID,omitempty"` - OrgID influxdb.ID `json:"orgID,omitempty"` - OwnerID influxdb.ID `json:"ownerID,omitempty"` - TaskID influxdb.ID `json:"taskID,omitempty"` + EndpointID platform.ID `json:"endpointID,omitempty"` + OrgID platform.ID `json:"orgID,omitempty"` + OwnerID platform.ID `json:"ownerID,omitempty"` + TaskID platform.ID `json:"taskID,omitempty"` // SleepUntil is an optional sleeptime to start a task. SleepUntil *time.Time `json:"sleepUntil,omitempty"` Every *notification.Duration `json:"every,omitempty"` @@ -64,38 +67,38 @@ type Base struct { func (b Base) valid() error { if !b.ID.Valid() { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Notification Rule ID is invalid", } } if b.Name == "" { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Notification Rule Name can't be empty", } } if !b.OwnerID.Valid() { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Notification Rule OwnerID is invalid", } } if !b.OrgID.Valid() { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Notification Rule OrgID is invalid", } } if !b.EndpointID.Valid() { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Notification Rule EndpointID is invalid", } } if b.Offset != nil && b.Every != nil && b.Offset.TimeDuration() >= b.Every.TimeDuration() { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Offset should not be equal or greater than the interval", } } @@ -106,8 +109,8 @@ func (b Base) valid() error { } if b.Limit != nil { if b.Limit.Every <= 0 || b.Limit.Rate <= 0 { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "if limit is set, limit and limitEvery must be larger than 0", } } @@ -308,27 +311,27 @@ func (b *Base) generateFluxASTStatuses() ast.Statement { } // GetID implements influxdb.Getter interface. -func (b Base) GetID() influxdb.ID { +func (b Base) GetID() platform.ID { return b.ID } // GetEndpointID gets the endpointID for a base. -func (b Base) GetEndpointID() influxdb.ID { +func (b Base) GetEndpointID() platform.ID { return b.EndpointID } // GetOrgID implements influxdb.Getter interface. -func (b Base) GetOrgID() influxdb.ID { +func (b Base) GetOrgID() platform.ID { return b.OrgID } // GetTaskID gets the task ID for a base. -func (b Base) GetTaskID() influxdb.ID { +func (b Base) GetTaskID() platform.ID { return b.TaskID } // SetTaskID sets the task ID for a base. -func (b *Base) SetTaskID(id influxdb.ID) { +func (b *Base) SetTaskID(id platform.ID) { b.TaskID = id } @@ -370,7 +373,7 @@ func (b *Base) MatchesTags(tags []influxdb.Tag) bool { } // GetOwnerID returns the owner id. -func (b Base) GetOwnerID() influxdb.ID { +func (b Base) GetOwnerID() platform.ID { return b.OwnerID } @@ -395,17 +398,17 @@ func (b *Base) GetDescription() string { } // SetID will set the primary key. -func (b *Base) SetID(id influxdb.ID) { +func (b *Base) SetID(id platform.ID) { b.ID = id } // SetOrgID will set the org key. -func (b *Base) SetOrgID(id influxdb.ID) { +func (b *Base) SetOrgID(id platform.ID) { b.OrgID = id } // SetOwnerID will set the owner id. -func (b *Base) SetOwnerID(id influxdb.ID) { +func (b *Base) SetOwnerID(id platform.ID) { b.OwnerID = id } diff --git a/notification/rule/rule_test.go b/notification/rule/rule_test.go index 91475cd950b..4dd2701288d 100644 --- a/notification/rule/rule_test.go +++ b/notification/rule/rule_test.go @@ -2,6 +2,7 @@ package rule_test import ( "encoding/json" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "testing" "time" @@ -41,8 +42,8 @@ func TestValidRule(t *testing.T) { { name: "invalid rule id", src: &rule.Slack{}, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "Notification Rule ID is invalid", }, }, @@ -53,8 +54,8 @@ func TestValidRule(t *testing.T) { ID: influxTesting.MustIDBase16(id1), }, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "Notification Rule Name can't be empty", }, }, @@ -66,8 +67,8 @@ func TestValidRule(t *testing.T) { Name: "name1", }, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "Notification Rule OwnerID is invalid", }, }, @@ -80,8 +81,8 @@ func TestValidRule(t *testing.T) { OwnerID: influxTesting.MustIDBase16(id2), }, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "Notification Rule OrgID is invalid", }, }, @@ -96,8 +97,8 @@ func TestValidRule(t *testing.T) { EndpointID: 0, }, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "Notification Rule EndpointID is invalid", }, }, @@ -114,8 +115,8 @@ func TestValidRule(t *testing.T) { Offset: mustDuration("2m"), }, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "Offset should not be equal or greater than the interval", }, }, @@ -125,8 +126,8 @@ func TestValidRule(t *testing.T) { Base: goodBase, Channel: "channel1", }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "slack msg template is empty", }, }, @@ -135,8 +136,8 @@ func TestValidRule(t *testing.T) { src: &rule.PagerDuty{ Base: goodBase, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "pagerduty invalid message template", }, }, @@ -161,8 +162,8 @@ func TestValidRule(t *testing.T) { }, MessageTemplate: "body {var2}", }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: `Operator is invalid`, }, }, @@ -190,8 +191,8 @@ func TestValidRule(t *testing.T) { }, MessageTemplate: "body {var2}", }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: `if limit is set, limit and limitEvery must be larger than 0`, }, }, diff --git a/notification/rule/service/service.go b/notification/rule/service/service.go index 4b2c3ce5f56..a2dd88393dd 100644 --- a/notification/rule/service/service.go +++ b/notification/rule/service/service.go @@ -5,6 +5,9 @@ import ( "encoding/json" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" "github.com/influxdata/influxdb/v2/notification/rule" @@ -17,15 +20,15 @@ var ( notificationRuleBucket = []byte("notificationRulev1") // ErrNotificationRuleNotFound is used when the notification rule is not found. - ErrNotificationRuleNotFound = &influxdb.Error{ + ErrNotificationRuleNotFound = &errors.Error{ Msg: "notification rule not found", - Code: influxdb.ENotFound, + Code: errors.ENotFound, } // ErrInvalidNotificationRuleID is used when the service was provided // an invalid ID format. - ErrInvalidNotificationRuleID = &influxdb.Error{ - Code: influxdb.EInvalid, + ErrInvalidNotificationRuleID = &errors.Error{ + Code: errors.EInvalid, Msg: "provided notification rule ID has invalid format", } ) @@ -40,7 +43,7 @@ type RuleService struct { orgs influxdb.OrganizationService endpoints influxdb.NotificationEndpointService - idGenerator influxdb.IDGenerator + idGenerator platform.IDGenerator timeGenerator influxdb.TimeGenerator } @@ -77,9 +80,9 @@ func (s *RuleService) initializeNotificationRule(ctx context.Context, tx kv.Tx) // UnavailableNotificationRuleStoreError is used if we aren't able to interact with the // store, it means the store is not available at the moment (e.g. network). -func UnavailableNotificationRuleStoreError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func UnavailableNotificationRuleStoreError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("Unable to connect to notification rule store service. Please try again; Err: %v", err), Op: "kv/notificationRule", } @@ -87,9 +90,9 @@ func UnavailableNotificationRuleStoreError(err error) *influxdb.Error { // InternalNotificationRuleStoreError is used when the error comes from an // internal system. -func InternalNotificationRuleStoreError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func InternalNotificationRuleStoreError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("Unknown internal notificationRule data error; Err: %v", err), Op: "kv/notificationRule", } @@ -104,7 +107,7 @@ func (s *RuleService) notificationRuleBucket(tx kv.Tx) (kv.Bucket, error) { } // CreateNotificationRule creates a new notification rule and sets b.ID with the new identifier. -func (s *RuleService) CreateNotificationRule(ctx context.Context, nr influxdb.NotificationRuleCreate, userID influxdb.ID) error { +func (s *RuleService) CreateNotificationRule(ctx context.Context, nr influxdb.NotificationRuleCreate, userID platform.ID) error { // set notification rule ID id := s.idGenerator.ID() nr.SetID(id) @@ -139,7 +142,7 @@ func (s *RuleService) CreateNotificationRule(ctx context.Context, nr influxdb.No return err } -func (s *RuleService) createNotificationRule(ctx context.Context, tx kv.Tx, nr influxdb.NotificationRuleCreate, userID influxdb.ID) error { +func (s *RuleService) createNotificationRule(ctx context.Context, tx kv.Tx, nr influxdb.NotificationRuleCreate, userID platform.ID) error { if err := nr.Valid(); err != nil { return err } @@ -181,7 +184,7 @@ func (s *RuleService) createNotificationTask(ctx context.Context, r influxdb.Not // UpdateNotificationRule updates a single notification rule. // Returns the new notification rule after update. -func (s *RuleService) UpdateNotificationRule(ctx context.Context, id influxdb.ID, nr influxdb.NotificationRuleCreate, userID influxdb.ID) (influxdb.NotificationRule, error) { +func (s *RuleService) UpdateNotificationRule(ctx context.Context, id platform.ID, nr influxdb.NotificationRuleCreate, userID platform.ID) (influxdb.NotificationRule, error) { rule, err := s.FindNotificationRuleByID(ctx, id) if err != nil { return nil, err @@ -242,7 +245,7 @@ func (s *RuleService) updateNotificationTask(ctx context.Context, r influxdb.Not // PatchNotificationRule updates a single notification rule with changeset. // Returns the new notification rule state after update. -func (s *RuleService) PatchNotificationRule(ctx context.Context, id influxdb.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { +func (s *RuleService) PatchNotificationRule(ctx context.Context, id platform.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { nr, err := s.FindNotificationRuleByID(ctx, id) if err != nil { return nil, err @@ -314,7 +317,7 @@ func (s *RuleService) putNotificationRule(ctx context.Context, tx kv.Tx, nr infl } // FindNotificationRuleByID returns a single notification rule by ID. -func (s *RuleService) FindNotificationRuleByID(ctx context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { +func (s *RuleService) FindNotificationRuleByID(ctx context.Context, id platform.ID) (influxdb.NotificationRule, error) { var ( nr influxdb.NotificationRule err error @@ -328,7 +331,7 @@ func (s *RuleService) FindNotificationRuleByID(ctx context.Context, id influxdb. return nr, err } -func (s *RuleService) findNotificationRuleByID(ctx context.Context, tx kv.Tx, id influxdb.ID) (influxdb.NotificationRule, error) { +func (s *RuleService) findNotificationRuleByID(ctx context.Context, tx kv.Tx, id platform.ID) (influxdb.NotificationRule, error) { encID, err := id.Encode() if err != nil { return nil, ErrInvalidNotificationRuleID @@ -455,7 +458,7 @@ func filterNotificationRulesFn(filter influxdb.NotificationRuleFilter) func(nr i } // DeleteNotificationRule removes a notification rule by ID. -func (s *RuleService) DeleteNotificationRule(ctx context.Context, id influxdb.ID) error { +func (s *RuleService) DeleteNotificationRule(ctx context.Context, id platform.ID) error { r, err := s.FindNotificationRuleByID(ctx, id) if err != nil { return err diff --git a/notification/rule/service/service_external_test.go b/notification/rule/service/service_external_test.go index 97f0c1d050c..835ff531c58 100644 --- a/notification/rule/service/service_external_test.go +++ b/notification/rule/service/service_external_test.go @@ -8,6 +8,9 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/influxdata/flux/ast" @@ -38,7 +41,7 @@ var ( // NotificationRuleFields includes prepopulated data for mapping tests. type NotificationRuleFields struct { - IDGenerator influxdb.IDGenerator + IDGenerator platform.IDGenerator TimeGenerator influxdb.TimeGenerator NotificationRules []influxdb.NotificationRule Orgs []*influxdb.Organization @@ -127,7 +130,7 @@ func CreateNotificationRule( ) { type args struct { notificationRule influxdb.NotificationRule - userID influxdb.ID + userID platform.ID } type wants struct { err error @@ -403,8 +406,8 @@ func CreateNotificationRule( }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "tag must contain a key and a value", }, }, @@ -480,7 +483,7 @@ func FindNotificationRuleByID( t *testing.T, ) { type args struct { - id influxdb.ID + id platform.ID } type wants struct { err error @@ -535,11 +538,11 @@ func FindNotificationRuleByID( }, }, args: args{ - id: influxdb.ID(0), + id: platform.ID(0), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "provided notification rule ID has invalid format", }, }, @@ -589,8 +592,8 @@ func FindNotificationRuleByID( id: MustIDBase16(threeID), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "notification rule not found", }, }, @@ -1234,8 +1237,8 @@ func UpdateNotificationRule( t *testing.T, ) { type args struct { - userID influxdb.ID - id influxdb.ID + userID platform.ID + id platform.ID notificationRule influxdb.NotificationRule } @@ -1309,8 +1312,8 @@ func UpdateNotificationRule( }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "notification rule not found", }, }, @@ -1480,7 +1483,7 @@ func PatchNotificationRule( type args struct { //userID influxdb.ID - id influxdb.ID + id platform.ID upd influxdb.NotificationRuleUpdate } @@ -1544,8 +1547,8 @@ func PatchNotificationRule( }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "notification rule not found", }, }, @@ -1823,8 +1826,8 @@ func DeleteNotificationRule( t *testing.T, ) { type args struct { - id influxdb.ID - orgID influxdb.ID + id platform.ID + orgID platform.ID } type wants struct { @@ -1879,12 +1882,12 @@ func DeleteNotificationRule( }, }, args: args{ - id: influxdb.ID(0), + id: platform.ID(0), orgID: MustIDBase16(fourID), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "provided notification rule ID has invalid format", }, notificationRules: []influxdb.NotificationRule{ @@ -1989,8 +1992,8 @@ func DeleteNotificationRule( orgID: MustIDBase16(fourID), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "notification rule not found", }, notificationRules: []influxdb.NotificationRule{ @@ -2153,8 +2156,8 @@ func DeleteNotificationRule( } // MustIDBase16 is an helper to ensure a correct ID is built during testing. -func MustIDBase16(s string) influxdb.ID { - id, err := influxdb.IDFromString(s) +func MustIDBase16(s string) platform.ID { + id, err := platform.IDFromString(s) if err != nil { panic(err) } @@ -2162,7 +2165,7 @@ func MustIDBase16(s string) influxdb.ID { } // MustIDBase16Ptr is an helper to ensure a correct *ID is built during testing. -func MustIDBase16Ptr(s string) *influxdb.ID { +func MustIDBase16Ptr(s string) *platform.ID { id := MustIDBase16(s) return &id } @@ -2182,18 +2185,18 @@ func ErrorsEqual(t *testing.T, actual, expected error) { t.Errorf("expected error %s but received nil", expected.Error()) } - if influxdb.ErrorCode(expected) != influxdb.ErrorCode(actual) { + if errors.ErrorCode(expected) != errors.ErrorCode(actual) { t.Logf("\nexpected: %v\nactual: %v\n\n", expected, actual) - t.Errorf("expected error code %q but received %q", influxdb.ErrorCode(expected), influxdb.ErrorCode(actual)) + t.Errorf("expected error code %q but received %q", errors.ErrorCode(expected), errors.ErrorCode(actual)) } - if influxdb.ErrorMessage(expected) != influxdb.ErrorMessage(actual) { + if errors.ErrorMessage(expected) != errors.ErrorMessage(actual) { t.Logf("\nexpected: %v\nactual: %v\n\n", expected, actual) - t.Errorf("expected error message %q but received %q", influxdb.ErrorMessage(expected), influxdb.ErrorMessage(actual)) + t.Errorf("expected error message %q but received %q", errors.ErrorMessage(expected), errors.ErrorMessage(actual)) } } -func idPtr(id influxdb.ID) *influxdb.ID { +func idPtr(id platform.ID) *platform.ID { return &id } diff --git a/notification/rule/service/service_test.go b/notification/rule/service/service_test.go index 8d500719bfb..d1d69a9518d 100644 --- a/notification/rule/service/service_test.go +++ b/notification/rule/service/service_test.go @@ -7,6 +7,8 @@ import ( "os" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + influxdb "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/bolt" _ "github.com/influxdata/influxdb/v2/fluxinit/static" @@ -136,7 +138,7 @@ func initNotificationRuleStore(s kv.Store, f NotificationRuleFields, t *testing. } } -func withOrgID(store *tenant.Store, orgID influxdb.ID, fn func()) { +func withOrgID(store *tenant.Store, orgID platform.ID, fn func()) { backup := store.OrgIDGen defer func() { store.OrgIDGen = backup }() diff --git a/notification/rule/slack.go b/notification/rule/slack.go index 518b2c74e8e..f962e166d6f 100644 --- a/notification/rule/slack.go +++ b/notification/rule/slack.go @@ -4,6 +4,8 @@ import ( "encoding/json" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/flux/ast" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/notification/endpoint" @@ -125,8 +127,8 @@ func (s Slack) Valid() error { return err } if s.MessageTemplate == "" { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "slack msg template is empty", } } diff --git a/notification/rule/slack_test.go b/notification/rule/slack_test.go index 88d4698edfb..529d0245a89 100644 --- a/notification/rule/slack_test.go +++ b/notification/rule/slack_test.go @@ -1,6 +1,7 @@ package rule_test import ( + "github.com/influxdata/influxdb/v2/kit/platform" "testing" "github.com/influxdata/flux/ast" @@ -24,8 +25,8 @@ func statusRulePtr(r notification.CheckLevel) *notification.CheckLevel { return &r } -func idPtr(i int) *influxdb.ID { - id := influxdb.ID(i) +func idPtr(i int) *platform.ID { + id := platform.ID(i) return &id } diff --git a/notification/rule/telegram.go b/notification/rule/telegram.go index fdfb5cc6700..e31c9b42342 100644 --- a/notification/rule/telegram.go +++ b/notification/rule/telegram.go @@ -4,6 +4,8 @@ import ( "encoding/json" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/flux/ast" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/notification/endpoint" @@ -126,8 +128,8 @@ func (s Telegram) Valid() error { return err } if s.MessageTemplate == "" { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Telegram MessageTemplate is invalid", } } diff --git a/notification/rule/telegram_test.go b/notification/rule/telegram_test.go index 05643bb429d..67945481035 100644 --- a/notification/rule/telegram_test.go +++ b/notification/rule/telegram_test.go @@ -1,6 +1,7 @@ package rule_test import ( + "github.com/influxdata/influxdb/v2/kit/platform/errors" "testing" "github.com/andreyvit/diff" @@ -268,8 +269,8 @@ func TestTelegram_Valid(t *testing.T) { TagRules: []notification.TagRule{}, }, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "Telegram MessageTemplate is invalid", }, }, @@ -292,8 +293,8 @@ func TestTelegram_Valid(t *testing.T) { TagRules: []notification.TagRule{}, }, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "Notification Rule EndpointID is invalid", }, }, diff --git a/notification_endpoint.go b/notification_endpoint.go index bcbcd3141ca..df5972d6d6b 100644 --- a/notification_endpoint.go +++ b/notification_endpoint.go @@ -4,6 +4,9 @@ import ( "context" "encoding/json" "errors" + + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" ) var ( @@ -18,15 +21,15 @@ type NotificationEndpoint interface { Type() string json.Marshaler CRUDLogSetter - SetID(id ID) - SetOrgID(id ID) + SetID(id platform.ID) + SetOrgID(id platform.ID) SetName(name string) SetDescription(description string) SetStatus(status Status) - GetID() ID + GetID() platform.ID GetCRUDLog() CRUDLog - GetOrgID() ID + GetOrgID() platform.ID GetName() string GetDescription() string GetStatus() Status @@ -49,8 +52,8 @@ var ( // NotificationEndpointFilter represents a set of filter that restrict the returned notification endpoints. type NotificationEndpointFilter struct { - ID *ID - OrgID *ID + ID *platform.ID + OrgID *platform.ID Org *string UserResourceMappingFilter } @@ -80,15 +83,15 @@ type NotificationEndpointUpdate struct { // Valid will verify if the NotificationEndpointUpdate is valid. func (n *NotificationEndpointUpdate) Valid() error { if n.Name != nil && *n.Name == "" { - return &Error{ - Code: EInvalid, + return &errors2.Error{ + Code: errors2.EInvalid, Msg: "Notification Endpoint Name can't be empty", } } if n.Description != nil && *n.Description == "" { - return &Error{ - Code: EInvalid, + return &errors2.Error{ + Code: errors2.EInvalid, Msg: "Notification Endpoint Description can't be empty", } } @@ -105,23 +108,23 @@ func (n *NotificationEndpointUpdate) Valid() error { // NotificationEndpointService represents a service for managing notification endpoints. type NotificationEndpointService interface { // FindNotificationEndpointByID returns a single notification endpoint by ID. - FindNotificationEndpointByID(ctx context.Context, id ID) (NotificationEndpoint, error) + FindNotificationEndpointByID(ctx context.Context, id platform.ID) (NotificationEndpoint, error) // FindNotificationEndpoints returns a list of notification endpoints that match filter and the total count of matching notification endpoints. // Additional options provide pagination & sorting. FindNotificationEndpoints(ctx context.Context, filter NotificationEndpointFilter, opt ...FindOptions) ([]NotificationEndpoint, int, error) // CreateNotificationEndpoint creates a new notification endpoint and sets b.ID with the new identifier. - CreateNotificationEndpoint(ctx context.Context, ne NotificationEndpoint, userID ID) error + CreateNotificationEndpoint(ctx context.Context, ne NotificationEndpoint, userID platform.ID) error // UpdateNotificationEndpoint updates a single notification endpoint. // Returns the new notification endpoint after update. - UpdateNotificationEndpoint(ctx context.Context, id ID, nr NotificationEndpoint, userID ID) (NotificationEndpoint, error) + UpdateNotificationEndpoint(ctx context.Context, id platform.ID, nr NotificationEndpoint, userID platform.ID) (NotificationEndpoint, error) // PatchNotificationEndpoint updates a single notification endpoint with changeset. // Returns the new notification endpoint state after update. - PatchNotificationEndpoint(ctx context.Context, id ID, upd NotificationEndpointUpdate) (NotificationEndpoint, error) + PatchNotificationEndpoint(ctx context.Context, id platform.ID, upd NotificationEndpointUpdate) (NotificationEndpoint, error) // DeleteNotificationEndpoint removes a notification endpoint by ID, returns secret fields, orgID for further deletion. - DeleteNotificationEndpoint(ctx context.Context, id ID) (flds []SecretField, orgID ID, err error) + DeleteNotificationEndpoint(ctx context.Context, id platform.ID) (flds []SecretField, orgID platform.ID, err error) } diff --git a/onboarding.go b/onboarding.go index f6047885942..4b265d36616 100644 --- a/onboarding.go +++ b/onboarding.go @@ -3,6 +3,8 @@ package influxdb import ( "context" "time" + + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) // OnboardingService represents a service for the first run. @@ -39,22 +41,22 @@ type OnboardingRequest struct { func (r *OnboardingRequest) Valid() error { if r.User == "" { - return &Error{ - Code: EEmptyValue, + return &errors.Error{ + Code: errors.EEmptyValue, Msg: "username is empty", } } if r.Org == "" { - return &Error{ - Code: EEmptyValue, + return &errors.Error{ + Code: errors.EEmptyValue, Msg: "org name is empty", } } if r.Bucket == "" { - return &Error{ - Code: EEmptyValue, + return &errors.Error{ + Code: errors.EEmptyValue, Msg: "bucket name is empty", } } diff --git a/operation_log.go b/operation_log.go index ab7b01139de..35a80d20174 100644 --- a/operation_log.go +++ b/operation_log.go @@ -3,37 +3,39 @@ package influxdb import ( "context" "time" + + "github.com/influxdata/influxdb/v2/kit/platform" ) // OperationLogEntry is a record in an operation log. type OperationLogEntry struct { - Description string `json:"description"` - UserID ID `json:"userID,omitempty"` - Time time.Time `json:"time,omitempty"` + Description string `json:"description"` + UserID platform.ID `json:"userID,omitempty"` + Time time.Time `json:"time,omitempty"` } // DashboardOperationLogService is an interface for retrieving the operation log for a dashboard. type DashboardOperationLogService interface { // GetDashboardOperationLog retrieves the operation log for the dashboard with the provided id. - GetDashboardOperationLog(ctx context.Context, id ID, opts FindOptions) ([]*OperationLogEntry, int, error) + GetDashboardOperationLog(ctx context.Context, id platform.ID, opts FindOptions) ([]*OperationLogEntry, int, error) } // BucketOperationLogService is an interface for retrieving the operation log for a bucket. type BucketOperationLogService interface { // GetBucketOperationLog retrieves the operation log for the bucket with the provided id. - GetBucketOperationLog(ctx context.Context, id ID, opts FindOptions) ([]*OperationLogEntry, int, error) + GetBucketOperationLog(ctx context.Context, id platform.ID, opts FindOptions) ([]*OperationLogEntry, int, error) } // UserOperationLogService is an interface for retrieving the operation log for a user. type UserOperationLogService interface { // GetUserOperationLog retrieves the operation log for the user with the provided id. - GetUserOperationLog(ctx context.Context, id ID, opts FindOptions) ([]*OperationLogEntry, int, error) + GetUserOperationLog(ctx context.Context, id platform.ID, opts FindOptions) ([]*OperationLogEntry, int, error) } // OrganizationOperationLogService is an interface for retrieving the operation log for an org. type OrganizationOperationLogService interface { // GetOrganizationOperationLog retrieves the operation log for the org with the provided id. - GetOrganizationOperationLog(ctx context.Context, id ID, opts FindOptions) ([]*OperationLogEntry, int, error) + GetOrganizationOperationLog(ctx context.Context, id platform.ID, opts FindOptions) ([]*OperationLogEntry, int, error) } // DefaultOperationLogFindOptions are the default options for the operation log. diff --git a/organization.go b/organization.go index a530c97b31e..74f07c71716 100644 --- a/organization.go +++ b/organization.go @@ -3,21 +3,24 @@ package influxdb import ( "context" "fmt" + + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) // Organization is an organization. 🎉 type Organization struct { - ID ID `json:"id,omitempty"` - Name string `json:"name"` - Description string `json:"description"` + ID platform.ID `json:"id,omitempty"` + Name string `json:"name"` + Description string `json:"description"` CRUDLog } // errors of org var ( // ErrOrgNameisEmpty is error when org name is empty - ErrOrgNameisEmpty = &Error{ - Code: EInvalid, + ErrOrgNameisEmpty = &errors.Error{ + Code: errors.EInvalid, Msg: "org name is empty", } ) @@ -36,7 +39,7 @@ const ( // OrganizationService represents a service for managing organization data. type OrganizationService interface { // Returns a single organization by ID. - FindOrganizationByID(ctx context.Context, id ID) (*Organization, error) + FindOrganizationByID(ctx context.Context, id platform.ID) (*Organization, error) // Returns the first organization that matches filter. FindOrganization(ctx context.Context, filter OrganizationFilter) (*Organization, error) @@ -50,10 +53,10 @@ type OrganizationService interface { // Updates a single organization with changeset. // Returns the new organization state after update. - UpdateOrganization(ctx context.Context, id ID, upd OrganizationUpdate) (*Organization, error) + UpdateOrganization(ctx context.Context, id platform.ID, upd OrganizationUpdate) (*Organization, error) // Removes a organization by ID. - DeleteOrganization(ctx context.Context, id ID) error + DeleteOrganization(ctx context.Context, id platform.ID) error } // OrganizationUpdate represents updates to a organization. @@ -64,21 +67,21 @@ type OrganizationUpdate struct { } // ErrInvalidOrgFilter is the error indicate org filter is empty -var ErrInvalidOrgFilter = &Error{ - Code: EInvalid, +var ErrInvalidOrgFilter = &errors.Error{ + Code: errors.EInvalid, Msg: "Please provide either orgID or org", } // OrganizationFilter represents a set of filter that restrict the returned results. type OrganizationFilter struct { Name *string - ID *ID - UserID *ID + ID *platform.ID + UserID *platform.ID } -func ErrInternalOrgServiceError(op string, err error) *Error { - return &Error{ - Code: EInternal, +func ErrInternalOrgServiceError(op string, err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("unexpected error in organizations; Err: %v", err), Op: op, Err: err, diff --git a/paging.go b/paging.go index 45e533f27fc..70582d26cfd 100644 --- a/paging.go +++ b/paging.go @@ -5,6 +5,9 @@ import ( "net/http" "net/url" "strconv" + + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) const ( @@ -29,7 +32,7 @@ type PagingLinks struct { type FindOptions struct { Limit int Offset int - After *ID + After *platform.ID SortBy string Descending bool } @@ -56,8 +59,8 @@ func DecodeFindOptions(r *http.Request) (*FindOptions, error) { if offset := qp.Get("offset"); offset != "" { o, err := strconv.Atoi(offset) if err != nil { - return nil, &Error{ - Code: EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "offset is invalid", } } @@ -66,10 +69,10 @@ func DecodeFindOptions(r *http.Request) (*FindOptions, error) { } if after := qp.Get("after"); after != "" { - id, err := IDFromString(after) + id, err := platform.IDFromString(after) if err != nil { - return nil, &Error{ - Code: EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: fmt.Errorf("decoding after: %w", err), } } @@ -80,15 +83,15 @@ func DecodeFindOptions(r *http.Request) (*FindOptions, error) { if limit := qp.Get("limit"); limit != "" { l, err := strconv.Atoi(limit) if err != nil { - return nil, &Error{ - Code: EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "limit is invalid", } } if l < 1 || l > MaxPageSize { - return nil, &Error{ - Code: EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("limit must be between 1 and %d", MaxPageSize), } } @@ -105,8 +108,8 @@ func DecodeFindOptions(r *http.Request) (*FindOptions, error) { if descending := qp.Get("descending"); descending != "" { desc, err := strconv.ParseBool(descending) if err != nil { - return nil, &Error{ - Code: EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "descending is invalid", } } diff --git a/passwords.go b/passwords.go index 8746db95663..06db283617c 100644 --- a/passwords.go +++ b/passwords.go @@ -1,15 +1,19 @@ package influxdb -import "context" +import ( + "context" + + "github.com/influxdata/influxdb/v2/kit/platform" +) // PasswordsService is the service for managing basic auth passwords. type PasswordsService interface { // SetPassword overrides the password of a known user. - SetPassword(ctx context.Context, userID ID, password string) error + SetPassword(ctx context.Context, userID platform.ID, password string) error // ComparePassword checks if the password matches the password recorded. // Passwords that do not match return errors. - ComparePassword(ctx context.Context, userID ID, password string) error + ComparePassword(ctx context.Context, userID platform.ID, password string) error // CompareAndSetPassword checks the password and if they match // updates to the new password. - CompareAndSetPassword(ctx context.Context, userID ID, old, new string) error + CompareAndSetPassword(ctx context.Context, userID platform.ID, old, new string) error } diff --git a/pkg/httpc/client.go b/pkg/httpc/client.go index 6b94001d479..955d354c909 100644 --- a/pkg/httpc/client.go +++ b/pkg/httpc/client.go @@ -7,7 +7,7 @@ import ( "net/url" "path" - "github.com/influxdata/influxdb/v2" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" ) type ( @@ -145,8 +145,8 @@ func (c *Client) Req(method string, bFn BodyFn, urlPath ...string) *Req { // TODO(@jsteenb2): add a inspection for an OK() or Valid() method, then enforce // that across all consumers? Same for all bodyFns for that matter. return &Req{ - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors2.Error{ + Code: errors2.EInvalid, Err: err, }, } diff --git a/pkg/httpc/req.go b/pkg/httpc/req.go index 300ab182795..792c3904904 100644 --- a/pkg/httpc/req.go +++ b/pkg/httpc/req.go @@ -11,7 +11,8 @@ import ( "net/http" "strings" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2/kit/tracing" ) @@ -190,8 +191,8 @@ func (r *Req) do(ctx context.Context) error { if r.decodeFn != nil { if err := r.decodeFn(resp); err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Err: err, } } diff --git a/pkg/jsonparser/jsonparser.go b/pkg/jsonparser/jsonparser.go index 410419c69ba..301ccc6d8cc 100644 --- a/pkg/jsonparser/jsonparser.go +++ b/pkg/jsonparser/jsonparser.go @@ -2,18 +2,18 @@ package jsonparser import ( "github.com/buger/jsonparser" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" ) // GetID returns an influxdb.ID for the specified keys path or an error if // the value cannot be decoded or does not exist. -func GetID(data []byte, keys ...string) (val influxdb.ID, err error) { +func GetID(data []byte, keys ...string) (val platform.ID, err error) { v, _, _, err := jsonparser.Get(data, keys...) if err != nil { return 0, err } - var id influxdb.ID + var id platform.ID err = id.Decode(v) if err != nil { return 0, err @@ -25,7 +25,7 @@ func GetID(data []byte, keys ...string) (val influxdb.ID, err error) { // GetOptionalID returns an influxdb.ID for the specified keys path or an error if // the value cannot be decoded. The value of exists will be false if the keys path // does not exist. -func GetOptionalID(data []byte, keys ...string) (val influxdb.ID, exists bool, err error) { +func GetOptionalID(data []byte, keys ...string) (val platform.ID, exists bool, err error) { v, typ, _, err := jsonparser.Get(data, keys...) if typ == jsonparser.NotExist { return 0, false, nil @@ -35,7 +35,7 @@ func GetOptionalID(data []byte, keys ...string) (val influxdb.ID, exists bool, e return 0, false, err } - var id influxdb.ID + var id platform.ID err = id.Decode(v) if err != nil { return 0, false, err diff --git a/pkg/jsonparser/jsonparser_test.go b/pkg/jsonparser/jsonparser_test.go index cb39d9aac15..8efba35f74d 100644 --- a/pkg/jsonparser/jsonparser_test.go +++ b/pkg/jsonparser/jsonparser_test.go @@ -1,10 +1,10 @@ package jsonparser_test import ( + "github.com/influxdata/influxdb/v2/kit/platform" "testing" "github.com/google/go-cmp/cmp" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/pkg/jsonparser" ) @@ -16,7 +16,7 @@ func TestGetID(t *testing.T) { t.Error("unexpected error:", err) } - if exp := influxdb.ID(10); got != exp { + if exp := platform.ID(10); got != exp { t.Error("unexpected value: -got/+exp", cmp.Diff(got, exp)) } }) diff --git a/pkger/clone_resource.go b/pkger/clone_resource.go index b4dde713252..efdeeb72bdc 100644 --- a/pkger/clone_resource.go +++ b/pkger/clone_resource.go @@ -8,6 +8,8 @@ import ( "sort" "strings" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ierrors "github.com/influxdata/influxdb/v2/kit/errors" "github.com/influxdata/influxdb/v2/notification" @@ -27,7 +29,7 @@ type NameGenerator func() string // ResourceToClone is a resource that will be cloned. type ResourceToClone struct { Kind Kind `json:"kind"` - ID influxdb.ID `json:"id,omitempty"` + ID platform.ID `json:"id,omitempty"` Name string `json:"name"` // note(jsteenb2): For time being we'll allow this internally, but not externally. A lot of // issues to account for when exposing this to the outside world. Not something I'm keen @@ -40,7 +42,7 @@ func (r ResourceToClone) OK() error { if err := r.Kind.OK(); err != nil { return err } - if r.ID == influxdb.ID(0) && len(r.Name) == 0 { + if r.ID == platform.ID(0) && len(r.Name) == 0 { return errors.New("must provide an ID or name") } return nil @@ -64,13 +66,13 @@ var kindPriorities = map[Kind]int{ } type exportKey struct { - orgID influxdb.ID - id influxdb.ID + orgID platform.ID + id platform.ID name string kind Kind } -func newExportKey(orgID, id influxdb.ID, k Kind, name string) exportKey { +func newExportKey(orgID, id platform.ID, k Kind, name string) exportKey { return exportKey{ orgID: orgID, id: id, @@ -116,7 +118,7 @@ func newResourceExporter(svc *Service) *resourceExporter { } func (ex *resourceExporter) Export(ctx context.Context, resourcesToClone []ResourceToClone, labelNames ...string) error { - mLabelIDsToMetaName := make(map[influxdb.ID]string) + mLabelIDsToMetaName := make(map[platform.ID]string) for _, r := range resourcesToClone { if !r.Kind.is(KindLabel) || r.MetaName == "" { continue @@ -174,7 +176,7 @@ func (ex *resourceExporter) StackResources() []StackResource { // we only need an id when we have resources that are not unique by name via the // metastore. resoureces that are unique by name will be provided a default stamp // making looksup unique since each resource will be unique by name. -const uniqByNameResID = influxdb.ID(0) +const uniqByNameResID = platform.ID(0) type cloneAssociationsFn func(context.Context, ResourceToClone) (associations []ObjectAssociation, skipResource bool, err error) @@ -193,7 +195,7 @@ func (ex *resourceExporter) resourceCloneToKind(ctx context.Context, r ResourceT return nil } - mapResource := func(orgID, uniqResID influxdb.ID, k Kind, object Object) { + mapResource := func(orgID, uniqResID platform.ID, k Kind, object Object) { // overwrite the default metadata.name field with export generated one here metaName := r.MetaName if r.MetaName == "" { @@ -220,7 +222,7 @@ func (ex *resourceExporter) resourceCloneToKind(ctx context.Context, r ResourceT switch { case r.Kind.is(KindBucket): filter := influxdb.BucketFilter{} - if r.ID != influxdb.ID(0) { + if r.ID != platform.ID(0) { filter.ID = &r.ID } if len(r.Name) > 0 { @@ -240,7 +242,7 @@ func (ex *resourceExporter) resourceCloneToKind(ctx context.Context, r ResourceT } case r.Kind.is(KindCheck), r.Kind.is(KindCheckDeadman), r.Kind.is(KindCheckThreshold): filter := influxdb.CheckFilter{} - if r.ID != influxdb.ID(0) { + if r.ID != platform.ID(0) { filter.ID = &r.ID } if len(r.Name) > 0 { @@ -262,9 +264,9 @@ func (ex *resourceExporter) resourceCloneToKind(ctx context.Context, r ResourceT hasID bool filter = influxdb.DashboardFilter{} ) - if r.ID != influxdb.ID(0) { + if r.ID != platform.ID(0) { hasID = true - filter.IDs = []*influxdb.ID{&r.ID} + filter.IDs = []*platform.ID{&r.ID} } dashes, _, err := ex.dashSVC.FindDashboards(ctx, filter, influxdb.DefaultDashboardFindOptions) @@ -295,7 +297,7 @@ func (ex *resourceExporter) resourceCloneToKind(ctx context.Context, r ResourceT } case r.Kind.is(KindLabel): switch { - case r.ID != influxdb.ID(0): + case r.ID != platform.ID(0): l, err := ex.labelSVC.FindLabelByID(ctx, r.ID) if err != nil { return err @@ -319,7 +321,7 @@ func (ex *resourceExporter) resourceCloneToKind(ctx context.Context, r ResourceT var endpoints []influxdb.NotificationEndpoint switch { - case r.ID != influxdb.ID(0): + case r.ID != platform.ID(0): notifEndpoint, err := ex.endpointSVC.FindNotificationEndpointByID(ctx, r.ID) if err != nil { return err @@ -350,7 +352,7 @@ func (ex *resourceExporter) resourceCloneToKind(ctx context.Context, r ResourceT var rules []influxdb.NotificationRule switch { - case r.ID != influxdb.ID(0): + case r.ID != platform.ID(0): r, err := ex.ruleSVC.FindNotificationRuleByID(ctx, r.ID) if err != nil { return err @@ -392,7 +394,7 @@ func (ex *resourceExporter) resourceCloneToKind(ctx context.Context, r ResourceT } case r.Kind.is(KindTask): switch { - case r.ID != influxdb.ID(0): + case r.ID != platform.ID(0): t, err := ex.taskSVC.FindTaskByID(ctx, r.ID) if err != nil { return err @@ -413,7 +415,7 @@ func (ex *resourceExporter) resourceCloneToKind(ctx context.Context, r ResourceT } case r.Kind.is(KindTelegraf): switch { - case r.ID != influxdb.ID(0): + case r.ID != platform.ID(0): t, err := ex.teleSVC.FindTelegrafConfigByID(ctx, r.ID) if err != nil { return err @@ -441,7 +443,7 @@ func (ex *resourceExporter) resourceCloneToKind(ctx context.Context, r ResourceT } case r.Kind.is(KindVariable): switch { - case r.ID != influxdb.ID(0): + case r.ID != platform.ID(0): v, err := ex.varSVC.FindVariableByID(ctx, r.ID) if err != nil { return err @@ -473,7 +475,7 @@ func (ex *resourceExporter) resourceCloneToKind(ctx context.Context, r ResourceT return nil } -func (ex *resourceExporter) resourceCloneAssociationsGen(ctx context.Context, labelIDsToMetaName map[influxdb.ID]string, labelNames ...string) (cloneAssociationsFn, error) { +func (ex *resourceExporter) resourceCloneAssociationsGen(ctx context.Context, labelIDsToMetaName map[platform.ID]string, labelNames ...string) (cloneAssociationsFn, error) { mLabelNames := make(map[string]bool) for _, labelName := range labelNames { mLabelNames[labelName] = true @@ -494,7 +496,7 @@ func (ex *resourceExporter) resourceCloneAssociationsGen(ctx context.Context, la return nil, shouldSkip, nil } - if len(r.Name) > 0 && r.ID == influxdb.ID(0) { + if len(r.Name) > 0 && r.ID == platform.ID(0) { return nil, false, nil } @@ -562,7 +564,7 @@ func (ex *resourceExporter) uniqName() string { return uniqMetaName(ex.nameGen, idGenerator, ex.mPkgNames) } -func uniqMetaName(nameGen NameGenerator, idGen influxdb.IDGenerator, existingNames map[string]bool) string { +func uniqMetaName(nameGen NameGenerator, idGen platform.IDGenerator, existingNames map[string]bool) string { uuid := strings.ToLower(idGen.ID().String()) name := uuid for i := 1; i < 250; i++ { @@ -577,7 +579,7 @@ func uniqMetaName(nameGen NameGenerator, idGen influxdb.IDGenerator, existingNam func uniqResourcesToClone(resources []ResourceToClone) []ResourceToClone { type key struct { kind Kind - id influxdb.ID + id platform.ID } m := make(map[key]ResourceToClone) diff --git a/pkger/http_remote_service.go b/pkger/http_remote_service.go index 8e4925b0e8d..fdd831b480d 100644 --- a/pkger/http_remote_service.go +++ b/pkger/http_remote_service.go @@ -5,7 +5,9 @@ import ( "encoding/json" "net/http" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + ihttp "github.com/influxdata/influxdb/v2/http" "github.com/influxdata/influxdb/v2/pkg/httpc" ) @@ -17,7 +19,7 @@ type HTTPRemoteService struct { var _ SVC = (*HTTPRemoteService)(nil) -func (s *HTTPRemoteService) InitStack(ctx context.Context, userID influxdb.ID, stack StackCreate) (Stack, error) { +func (s *HTTPRemoteService) InitStack(ctx context.Context, userID platform.ID, stack StackCreate) (Stack, error) { reqBody := ReqCreateStack{ OrgID: stack.OrgID.String(), Name: stack.Name, @@ -37,7 +39,7 @@ func (s *HTTPRemoteService) InitStack(ctx context.Context, userID influxdb.ID, s return convertRespStackToStack(respBody) } -func (s *HTTPRemoteService) UninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) (Stack, error) { +func (s *HTTPRemoteService) UninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) (Stack, error) { var respBody RespStack err := s.Client. Post(httpc.BodyEmpty, RoutePrefixStacks, identifiers.StackID.String(), "/uninstall"). @@ -51,14 +53,14 @@ func (s *HTTPRemoteService) UninstallStack(ctx context.Context, identifiers stru return convertRespStackToStack(respBody) } -func (s *HTTPRemoteService) DeleteStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) error { +func (s *HTTPRemoteService) DeleteStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) error { return s.Client. Delete(RoutePrefixStacks, identifiers.StackID.String()). QueryParams([2]string{"orgID", identifiers.OrgID.String()}). Do(ctx) } -func (s *HTTPRemoteService) ListStacks(ctx context.Context, orgID influxdb.ID, f ListFilter) ([]Stack, error) { +func (s *HTTPRemoteService) ListStacks(ctx context.Context, orgID platform.ID, f ListFilter) ([]Stack, error) { queryParams := [][2]string{{"orgID", orgID.String()}} for _, name := range f.Names { queryParams = append(queryParams, [2]string{"name", name}) @@ -88,7 +90,7 @@ func (s *HTTPRemoteService) ListStacks(ctx context.Context, orgID influxdb.ID, f return out, nil } -func (s *HTTPRemoteService) ReadStack(ctx context.Context, id influxdb.ID) (Stack, error) { +func (s *HTTPRemoteService) ReadStack(ctx context.Context, id platform.ID) (Stack, error) { var respBody RespStack err := s.Client. Get(RoutePrefixStacks, id.String()). @@ -175,18 +177,18 @@ func (s *HTTPRemoteService) Export(ctx context.Context, opts ...ExportOptFn) (*T // DryRun provides a dry run of the template application. The template will be marked verified // for later calls to Apply. This func will be run on an Apply if it has not been run // already. -func (s *HTTPRemoteService) DryRun(ctx context.Context, orgID, userID influxdb.ID, opts ...ApplyOptFn) (ImpactSummary, error) { +func (s *HTTPRemoteService) DryRun(ctx context.Context, orgID, userID platform.ID, opts ...ApplyOptFn) (ImpactSummary, error) { return s.apply(ctx, orgID, true, opts...) } // Apply will apply all the resources identified in the provided template. The entire template will be applied // in its entirety. If a failure happens midway then the entire template will be rolled back to the state // from before the template was applied. -func (s *HTTPRemoteService) Apply(ctx context.Context, orgID, userID influxdb.ID, opts ...ApplyOptFn) (ImpactSummary, error) { +func (s *HTTPRemoteService) Apply(ctx context.Context, orgID, userID platform.ID, opts ...ApplyOptFn) (ImpactSummary, error) { return s.apply(ctx, orgID, false, opts...) } -func (s *HTTPRemoteService) apply(ctx context.Context, orgID influxdb.ID, dryRun bool, opts ...ApplyOptFn) (ImpactSummary, error) { +func (s *HTTPRemoteService) apply(ctx context.Context, orgID platform.ID, dryRun bool, opts ...ApplyOptFn) (ImpactSummary, error) { opt := applyOptFromOptFns(opts...) var rawTemplate ReqRawTemplate @@ -215,7 +217,7 @@ func (s *HTTPRemoteService) apply(ctx context.Context, orgID influxdb.ID, dryRun for act := range opt.ResourcesToSkip { b, err := json.Marshal(act) if err != nil { - return ImpactSummary{}, influxErr(influxdb.EInvalid, err) + return ImpactSummary{}, influxErr(errors.EInvalid, err) } reqBody.RawActions = append(reqBody.RawActions, ReqRawAction{ Action: string(ActionTypeSkipResource), @@ -225,7 +227,7 @@ func (s *HTTPRemoteService) apply(ctx context.Context, orgID influxdb.ID, dryRun for kind := range opt.KindsToSkip { b, err := json.Marshal(ActionSkipKind{Kind: kind}) if err != nil { - return ImpactSummary{}, influxErr(influxdb.EInvalid, err) + return ImpactSummary{}, influxErr(errors.EInvalid, err) } reqBody.RawActions = append(reqBody.RawActions, ReqRawAction{ Action: string(ActionTypeSkipKind), @@ -257,7 +259,7 @@ func (s *HTTPRemoteService) apply(ctx context.Context, orgID influxdb.ID, dryRun Summary: resp.Summary, } - if stackID, err := influxdb.IDFromString(resp.StackID); err == nil { + if stackID, err := platform.IDFromString(resp.StackID); err == nil { impact.StackID = *stackID } @@ -268,13 +270,13 @@ func convertRespStackToStack(respStack RespStack) (Stack, error) { newStack := Stack{ CreatedAt: respStack.CreatedAt, } - id, err := influxdb.IDFromString(respStack.ID) + id, err := platform.IDFromString(respStack.ID) if err != nil { return Stack{}, err } newStack.ID = *id - orgID, err := influxdb.IDFromString(respStack.OrgID) + orgID, err := platform.IDFromString(respStack.OrgID) if err != nil { return Stack{}, err } @@ -333,9 +335,9 @@ func convertRespStackResources(resources []RespStackResource) ([]StackResource, sr.Associations = append(sr.Associations, StackResourceAssociation(a)) } - resID, err := influxdb.IDFromString(r.ID) + resID, err := platform.IDFromString(r.ID) if err != nil { - return nil, influxErr(influxdb.EInternal, err) + return nil, influxErr(errors.EInternal, err) } sr.ID = *resID diff --git a/pkger/http_server_stack.go b/pkger/http_server_stack.go index ece1011a570..ddc9364115a 100644 --- a/pkger/http_server_stack.go +++ b/pkger/http_server_stack.go @@ -7,8 +7,10 @@ import ( "path" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" - "github.com/influxdata/influxdb/v2" pctx "github.com/influxdata/influxdb/v2/context" kithttp "github.com/influxdata/influxdb/v2/kit/transport/http" "go.uber.org/zap" @@ -109,10 +111,10 @@ func (s *HTTPServerStacks) listStacks(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() rawOrgID := q.Get("orgID") - orgID, err := influxdb.IDFromString(rawOrgID) + orgID, err := platform.IDFromString(rawOrgID) if err != nil { - s.api.Err(w, r, &influxdb.Error{ - Code: influxdb.EInvalid, + s.api.Err(w, r, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("organization id[%q] is invalid", rawOrgID), Err: err, }) @@ -120,8 +122,8 @@ func (s *HTTPServerStacks) listStacks(w http.ResponseWriter, r *http.Request) { } if err := r.ParseForm(); err != nil { - s.api.Err(w, r, &influxdb.Error{ - Code: influxdb.EInvalid, + s.api.Err(w, r, &errors.Error{ + Code: errors.EInvalid, Msg: "failed to parse form from encoded url", Err: err, }) @@ -133,10 +135,10 @@ func (s *HTTPServerStacks) listStacks(w http.ResponseWriter, r *http.Request) { } for _, idRaw := range r.Form["stackID"] { - id, err := influxdb.IDFromString(idRaw) + id, err := platform.IDFromString(idRaw) if err != nil { - s.api.Err(w, r, &influxdb.Error{ - Code: influxdb.EInvalid, + s.api.Err(w, r, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("stack ID[%q] provided is invalid", idRaw), Err: err, }) @@ -175,17 +177,17 @@ type ReqCreateStack struct { // OK validates the request body is valid. func (r *ReqCreateStack) OK() error { // TODO: provide multiple errors back for failing validation - if _, err := influxdb.IDFromString(r.OrgID); err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + if _, err := platform.IDFromString(r.OrgID); err != nil { + return &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("provided org id[%q] is invalid", r.OrgID), } } for _, u := range r.URLs { if _, err := url.Parse(u); err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("provided url[%q] is invalid", u), } } @@ -193,8 +195,8 @@ func (r *ReqCreateStack) OK() error { return nil } -func (r *ReqCreateStack) orgID() influxdb.ID { - orgID, _ := influxdb.IDFromString(r.OrgID) +func (r *ReqCreateStack) orgID() platform.ID { + orgID, _ := platform.IDFromString(r.OrgID) return *orgID } @@ -245,7 +247,7 @@ func (s *HTTPServerStacks) deleteStack(w http.ResponseWriter, r *http.Request) { return } - err = s.svc.DeleteStack(r.Context(), struct{ OrgID, UserID, StackID influxdb.ID }{ + err = s.svc.DeleteStack(r.Context(), struct{ OrgID, UserID, StackID platform.ID }{ OrgID: orgID, UserID: auth.GetUserID(), StackID: stackID, @@ -277,7 +279,7 @@ func (s *HTTPServerStacks) uninstallStack(w http.ResponseWriter, r *http.Request return } - stack, err := s.svc.UninstallStack(r.Context(), struct{ OrgID, UserID, StackID influxdb.ID }{ + stack, err := s.svc.UninstallStack(r.Context(), struct{ OrgID, UserID, StackID platform.ID }{ OrgID: orgID, UserID: auth.GetUserID(), StackID: stackID, @@ -346,9 +348,9 @@ func (s *HTTPServerStacks) updateStack(w http.ResponseWriter, r *http.Request) { TemplateURLs: append(req.TemplateURLs, req.URLs...), } for _, res := range req.AdditionalResources { - id, err := influxdb.IDFromString(res.ID) + id, err := platform.IDFromString(res.ID) if err != nil { - s.api.Err(w, r, influxErr(influxdb.EInvalid, err, fmt.Sprintf("stack resource id %q", res.ID))) + s.api.Err(w, r, influxErr(errors.EInvalid, err, fmt.Sprintf("stack resource id %q", res.ID))) return } update.AdditionalResources = append(update.AdditionalResources, StackAdditionalResource{ @@ -441,11 +443,11 @@ func stackResLinks(r StackResource) RespStackResourceLinks { } } -func stackIDFromReq(r *http.Request) (influxdb.ID, error) { - stackID, err := influxdb.IDFromString(chi.URLParam(r, "stack_id")) +func stackIDFromReq(r *http.Request) (platform.ID, error) { + stackID, err := platform.IDFromString(chi.URLParam(r, "stack_id")) if err != nil { - return 0, &influxdb.Error{ - Code: influxdb.EInvalid, + return 0, &errors.Error{ + Code: errors.EInvalid, Msg: "the stack id provided in the path was invalid", Err: err, } @@ -453,19 +455,19 @@ func stackIDFromReq(r *http.Request) (influxdb.ID, error) { return *stackID, nil } -func getRequiredOrgIDFromQuery(q url.Values) (influxdb.ID, error) { +func getRequiredOrgIDFromQuery(q url.Values) (platform.ID, error) { orgIDRaw := q.Get("orgID") if orgIDRaw == "" { - return 0, &influxdb.Error{ - Code: influxdb.EInvalid, + return 0, &errors.Error{ + Code: errors.EInvalid, Msg: "the orgID query param is required", } } - orgID, err := influxdb.IDFromString(orgIDRaw) + orgID, err := platform.IDFromString(orgIDRaw) if err != nil { - return 0, &influxdb.Error{ - Code: influxdb.EInvalid, + return 0, &errors.Error{ + Code: errors.EInvalid, Msg: "the orgID query param was invalid", Err: err, } diff --git a/pkger/http_server_stack_test.go b/pkger/http_server_stack_test.go index ae926501414..c4e99e1e615 100644 --- a/pkger/http_server_stack_test.go +++ b/pkger/http_server_stack_test.go @@ -5,6 +5,8 @@ import ( "context" "errors" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" "io/ioutil" "net/http" "net/http/httptest" @@ -12,7 +14,6 @@ import ( "testing" "time" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/pkg/testttp" "github.com/influxdata/influxdb/v2/pkger" "github.com/stretchr/testify/assert" @@ -37,7 +38,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { return &s } - newStackEvent := func(id influxdb.ID, k pkger.Kind, metaName string, associations ...pkger.RespStackResourceAssoc) pkger.RespStackResource { + newStackEvent := func(id platform.ID, k pkger.Kind, metaName string, associations ...pkger.RespStackResourceAssoc) pkger.RespStackResource { if associations == nil { associations = []pkger.RespStackResourceAssoc{} } @@ -54,7 +55,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { t.Run("create a stack", func(t *testing.T) { t.Run("should successfully return with valid req body", func(t *testing.T) { svc := &fakeSVC{ - initStackFn: func(ctx context.Context, userID influxdb.ID, stackCr pkger.StackCreate) (pkger.Stack, error) { + initStackFn: func(ctx context.Context, userID platform.ID, stackCr pkger.StackCreate) (pkger.Stack, error) { return pkger.Stack{ ID: 2, OrgID: stackCr.OrgID, @@ -75,7 +76,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { svr := newMountedHandler(pkgHandler, 1) reqBody := pkger.ReqCreateStack{ - OrgID: influxdb.ID(3).String(), + OrgID: platform.ID(3).String(), Name: "threeve", Description: "desc", URLs: []string{"http://example.com"}, @@ -119,27 +120,27 @@ func TestPkgerHTTPServerStacks(t *testing.T) { { name: "bad url", reqBody: pkger.ReqCreateStack{ - OrgID: influxdb.ID(3).String(), + OrgID: platform.ID(3).String(), URLs: []string{"invalid @% url"}, }, expectedStatus: http.StatusBadRequest, }, { name: "translates svc conflict error", - reqBody: pkger.ReqCreateStack{OrgID: influxdb.ID(3).String()}, + reqBody: pkger.ReqCreateStack{OrgID: platform.ID(3).String()}, svc: &fakeSVC{ - initStackFn: func(ctx context.Context, userID influxdb.ID, stack pkger.StackCreate) (pkger.Stack, error) { - return pkger.Stack{}, &influxdb.Error{Code: influxdb.EConflict} + initStackFn: func(ctx context.Context, userID platform.ID, stack pkger.StackCreate) (pkger.Stack, error) { + return pkger.Stack{}, &errors2.Error{Code: errors2.EConflict} }, }, expectedStatus: http.StatusUnprocessableEntity, }, { name: "translates svc internal error", - reqBody: pkger.ReqCreateStack{OrgID: influxdb.ID(3).String()}, + reqBody: pkger.ReqCreateStack{OrgID: platform.ID(3).String()}, svc: &fakeSVC{ - initStackFn: func(ctx context.Context, userID influxdb.ID, stack pkger.StackCreate) (pkger.Stack, error) { - return pkger.Stack{}, &influxdb.Error{Code: influxdb.EInternal} + initStackFn: func(ctx context.Context, userID platform.ID, stack pkger.StackCreate) (pkger.Stack, error) { + return pkger.Stack{}, &errors2.Error{Code: errors2.EInternal} }, }, expectedStatus: http.StatusInternalServerError, @@ -151,7 +152,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { svc := tt.svc if svc == nil { svc = &fakeSVC{ - initStackFn: func(ctx context.Context, userID influxdb.ID, stack pkger.StackCreate) (pkger.Stack, error) { + initStackFn: func(ctx context.Context, userID platform.ID, stack pkger.StackCreate) (pkger.Stack, error) { return pkger.Stack{}, nil }, } @@ -174,10 +175,10 @@ func TestPkgerHTTPServerStacks(t *testing.T) { t.Run("list a stack", func(t *testing.T) { t.Run("should successfully return with valid req body", func(t *testing.T) { - const expectedOrgID influxdb.ID = 3 + const expectedOrgID platform.ID = 3 svc := &fakeSVC{ - listStacksFn: func(ctx context.Context, orgID influxdb.ID, filter pkger.ListFilter) ([]pkger.Stack, error) { + listStacksFn: func(ctx context.Context, orgID platform.ID, filter pkger.ListFilter) ([]pkger.Stack, error) { if orgID != expectedOrgID { return nil, nil } @@ -186,7 +187,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { var stacks []pkger.Stack for i, name := range filter.Names { stacks = append(stacks, pkger.Stack{ - ID: influxdb.ID(i + 1), + ID: platform.ID(i + 1), OrgID: expectedOrgID, Events: []pkger.StackEvent{ { @@ -232,7 +233,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { name: "with org ID that has stacks", queryArgs: "orgID=" + expectedOrgID.String(), expectedStacks: []pkger.RespStack{{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -254,7 +255,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }, { name: "with orgID with no stacks", - queryArgs: "orgID=" + influxdb.ID(9000).String(), + queryArgs: "orgID=" + platform.ID(9000).String(), expectedStacks: []pkger.RespStack{}, }, { @@ -262,7 +263,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { queryArgs: "name=name_stack&name=threeve&orgID=" + expectedOrgID.String(), expectedStacks: []pkger.RespStack{ { - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -282,7 +283,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }, }, { - ID: influxdb.ID(2).String(), + ID: platform.ID(2).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -305,10 +306,10 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }, { name: "with ids", - queryArgs: fmt.Sprintf("stackID=%s&stackID=%s&orgID=%s", influxdb.ID(1), influxdb.ID(2), influxdb.ID(expectedOrgID)), + queryArgs: fmt.Sprintf("stackID=%s&stackID=%s&orgID=%s", platform.ID(1), platform.ID(2), platform.ID(expectedOrgID)), expectedStacks: []pkger.RespStack{ { - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -326,7 +327,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }, }, { - ID: influxdb.ID(2).String(), + ID: platform.ID(2).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -367,7 +368,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }) t.Run("should provide all resource links for each stack resource collection", func(t *testing.T) { - const expectedOrgID influxdb.ID = 3 + const expectedOrgID platform.ID = 3 tests := []struct { name string @@ -391,7 +392,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -436,7 +437,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -477,7 +478,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -516,7 +517,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -573,7 +574,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -618,7 +619,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -657,7 +658,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -696,7 +697,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -735,7 +736,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -762,7 +763,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { svc := &fakeSVC{ - listStacksFn: func(ctx context.Context, orgID influxdb.ID, filter pkger.ListFilter) ([]pkger.Stack, error) { + listStacksFn: func(ctx context.Context, orgID platform.ID, filter pkger.ListFilter) ([]pkger.Stack, error) { return []pkger.Stack{tt.stub}, nil }, } @@ -789,7 +790,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { t.Run("read a stack", func(t *testing.T) { t.Run("should successfully return with valid req body", func(t *testing.T) { - const expectedOrgID influxdb.ID = 3 + const expectedOrgID platform.ID = 3 tests := []struct { name string @@ -819,7 +820,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -858,7 +859,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -888,7 +889,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { Events: []pkger.StackEvent{{}}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -929,7 +930,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -970,7 +971,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -1009,7 +1010,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -1066,7 +1067,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -1111,7 +1112,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -1150,7 +1151,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -1189,7 +1190,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -1228,7 +1229,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventCreate.String(), @@ -1255,7 +1256,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { svc := &fakeSVC{ - readStackFn: func(ctx context.Context, id influxdb.ID) (pkger.Stack, error) { + readStackFn: func(ctx context.Context, id platform.ID) (pkger.Stack, error) { return tt.stub, nil }, } @@ -1292,10 +1293,10 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }, { name: "stack not found", - stackIDPath: influxdb.ID(1).String(), + stackIDPath: platform.ID(1).String(), svc: &fakeSVC{ - readStackFn: func(ctx context.Context, id influxdb.ID) (pkger.Stack, error) { - return pkger.Stack{}, &influxdb.Error{Code: influxdb.ENotFound} + readStackFn: func(ctx context.Context, id platform.ID) (pkger.Stack, error) { + return pkger.Stack{}, &errors2.Error{Code: errors2.ENotFound} }, }, expectedStatus: http.StatusNotFound, @@ -1307,7 +1308,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { svc := tt.svc if svc == nil { svc = &fakeSVC{ - initStackFn: func(ctx context.Context, userID influxdb.ID, stack pkger.StackCreate) (pkger.Stack, error) { + initStackFn: func(ctx context.Context, userID platform.ID, stack pkger.StackCreate) (pkger.Stack, error) { return pkger.Stack{}, nil }, } @@ -1330,7 +1331,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { t.Run("update a stack", func(t *testing.T) { t.Run("should successfully update with valid req body", func(t *testing.T) { - const expectedOrgID influxdb.ID = 3 + const expectedOrgID platform.ID = 3 tests := []struct { name string @@ -1343,7 +1344,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { Name: strPtr("name"), }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventUpdate.String(), @@ -1369,7 +1370,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { Description: strPtr("desc"), }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventUpdate.String(), @@ -1395,7 +1396,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { TemplateURLs: []string{"http://example.com"}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventUpdate.String(), @@ -1421,7 +1422,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { TemplateURLs: []string{"http://example.com"}, }, expectedStack: pkger.RespStack{ - ID: influxdb.ID(1).String(), + ID: platform.ID(1).String(), OrgID: expectedOrgID.String(), RespStackEvent: pkger.RespStackEvent{ EventType: pkger.StackEventUpdate.String(), @@ -1447,7 +1448,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { - id, err := influxdb.IDFromString(tt.expectedStack.ID) + id, err := platform.IDFromString(tt.expectedStack.ID) require.NoError(t, err) svc := &fakeSVC{ @@ -1506,10 +1507,10 @@ func TestPkgerHTTPServerStacks(t *testing.T) { }, { name: "stack not found", - stackIDPath: influxdb.ID(1).String(), + stackIDPath: platform.ID(1).String(), svc: &fakeSVC{ - readStackFn: func(ctx context.Context, id influxdb.ID) (pkger.Stack, error) { - return pkger.Stack{}, &influxdb.Error{Code: influxdb.ENotFound} + readStackFn: func(ctx context.Context, id platform.ID) (pkger.Stack, error) { + return pkger.Stack{}, &errors2.Error{Code: errors2.ENotFound} }, }, expectedStatus: http.StatusNotFound, @@ -1521,7 +1522,7 @@ func TestPkgerHTTPServerStacks(t *testing.T) { svc := tt.svc if svc == nil { svc = &fakeSVC{ - initStackFn: func(ctx context.Context, userID influxdb.ID, stack pkger.StackCreate) (pkger.Stack, error) { + initStackFn: func(ctx context.Context, userID platform.ID, stack pkger.StackCreate) (pkger.Stack, error) { return pkger.Stack{}, nil }, } @@ -1544,39 +1545,39 @@ func TestPkgerHTTPServerStacks(t *testing.T) { } type fakeSVC struct { - initStackFn func(ctx context.Context, userID influxdb.ID, stack pkger.StackCreate) (pkger.Stack, error) - listStacksFn func(ctx context.Context, orgID influxdb.ID, filter pkger.ListFilter) ([]pkger.Stack, error) - readStackFn func(ctx context.Context, id influxdb.ID) (pkger.Stack, error) + initStackFn func(ctx context.Context, userID platform.ID, stack pkger.StackCreate) (pkger.Stack, error) + listStacksFn func(ctx context.Context, orgID platform.ID, filter pkger.ListFilter) ([]pkger.Stack, error) + readStackFn func(ctx context.Context, id platform.ID) (pkger.Stack, error) updateStackFn func(ctx context.Context, upd pkger.StackUpdate) (pkger.Stack, error) - dryRunFn func(ctx context.Context, orgID, userID influxdb.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) - applyFn func(ctx context.Context, orgID, userID influxdb.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) + dryRunFn func(ctx context.Context, orgID, userID platform.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) + applyFn func(ctx context.Context, orgID, userID platform.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) } var _ pkger.SVC = (*fakeSVC)(nil) -func (f *fakeSVC) InitStack(ctx context.Context, userID influxdb.ID, stack pkger.StackCreate) (pkger.Stack, error) { +func (f *fakeSVC) InitStack(ctx context.Context, userID platform.ID, stack pkger.StackCreate) (pkger.Stack, error) { if f.initStackFn == nil { panic("not implemented") } return f.initStackFn(ctx, userID, stack) } -func (f *fakeSVC) UninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) (pkger.Stack, error) { +func (f *fakeSVC) UninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) (pkger.Stack, error) { panic("not implemented") } -func (f *fakeSVC) DeleteStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) error { +func (f *fakeSVC) DeleteStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) error { panic("not implemented yet") } -func (f *fakeSVC) ListStacks(ctx context.Context, orgID influxdb.ID, filter pkger.ListFilter) ([]pkger.Stack, error) { +func (f *fakeSVC) ListStacks(ctx context.Context, orgID platform.ID, filter pkger.ListFilter) ([]pkger.Stack, error) { if f.listStacksFn == nil { panic("not implemented") } return f.listStacksFn(ctx, orgID, filter) } -func (f *fakeSVC) ReadStack(ctx context.Context, id influxdb.ID) (pkger.Stack, error) { +func (f *fakeSVC) ReadStack(ctx context.Context, id platform.ID) (pkger.Stack, error) { if f.readStackFn != nil { return f.readStackFn(ctx, id) } @@ -1594,7 +1595,7 @@ func (f *fakeSVC) Export(ctx context.Context, setters ...pkger.ExportOptFn) (*pk panic("not implemented") } -func (f *fakeSVC) DryRun(ctx context.Context, orgID, userID influxdb.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { +func (f *fakeSVC) DryRun(ctx context.Context, orgID, userID platform.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { if f.dryRunFn == nil { panic("not implemented") } @@ -1602,14 +1603,14 @@ func (f *fakeSVC) DryRun(ctx context.Context, orgID, userID influxdb.ID, opts .. return f.dryRunFn(ctx, orgID, userID, opts...) } -func (f *fakeSVC) Apply(ctx context.Context, orgID, userID influxdb.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { +func (f *fakeSVC) Apply(ctx context.Context, orgID, userID platform.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { if f.applyFn == nil { panic("not implemented") } return f.applyFn(ctx, orgID, userID, opts...) } -func stackResLinks(resource string, id influxdb.ID) pkger.RespStackResourceLinks { +func stackResLinks(resource string, id platform.ID) pkger.RespStackResourceLinks { return pkger.RespStackResourceLinks{ Self: fmt.Sprintf("/api/v2/%s/%s", resource, id), } diff --git a/pkger/http_server_template.go b/pkger/http_server_template.go index 2b98b2ef2d3..ff8ae262b7a 100644 --- a/pkger/http_server_template.go +++ b/pkger/http_server_template.go @@ -9,9 +9,11 @@ import ( "path" "strings" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" - "github.com/influxdata/influxdb/v2" pctx "github.com/influxdata/influxdb/v2/context" ierrors "github.com/influxdata/influxdb/v2/kit/errors" kithttp "github.com/influxdata/influxdb/v2/kit/transport/http" @@ -75,23 +77,23 @@ type ReqExport struct { // OK validates a create request. func (r *ReqExport) OK() error { if len(r.Resources) == 0 && len(r.OrgIDs) == 0 && r.StackID == "" { - return &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + return &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: "at least 1 resource, 1 org id, or stack id must be provided", } } for _, org := range r.OrgIDs { - if _, err := influxdb.IDFromString(org.OrgID); err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + if _, err := platform.IDFromString(org.OrgID); err != nil { + return &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("provided org id is invalid: %q", org.OrgID), } } } if r.StackID != "" { - _, err := influxdb.IDFromString(r.StackID) + _, err := platform.IDFromString(r.StackID) return err } return nil @@ -112,7 +114,7 @@ func (s *HTTPServerTemplates) export(w http.ResponseWriter, r *http.Request) { ExportWithExistingResources(reqBody.Resources...), } for _, orgIDStr := range reqBody.OrgIDs { - orgID, err := influxdb.IDFromString(orgIDStr.OrgID) + orgID, err := platform.IDFromString(orgIDStr.OrgID) if err != nil { continue } @@ -124,10 +126,10 @@ func (s *HTTPServerTemplates) export(w http.ResponseWriter, r *http.Request) { } if reqBody.StackID != "" { - stackID, err := influxdb.IDFromString(reqBody.StackID) + stackID, err := platform.IDFromString(reqBody.StackID) if err != nil { - s.api.Err(w, r, &influxdb.Error{ - Code: influxdb.EInvalid, + s.api.Err(w, r, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("invalid stack ID provided: %q", reqBody.StackID), }) return @@ -219,7 +221,7 @@ func (r ReqApply) Templates(encoding Encoding) (*Template, error) { template, err := Parse(rem.Encoding(), FromHTTPRequest(rem.URL), ValidSkipParseError()) if err != nil { msg := fmt.Sprintf("template from url[%s] had an issue: %s", rem.URL, err.Error()) - return nil, influxErr(influxdb.EUnprocessableEntity, msg) + return nil, influxErr(errors.EUnprocessableEntity, msg) } rawTemplates = append(rawTemplates, template) } @@ -236,7 +238,7 @@ func (r ReqApply) Templates(encoding Encoding) (*Template, error) { if err != nil { sources := formatSources(rawTmpl.Sources) msg := fmt.Sprintf("template[%d] from source(s) %q had an issue: %s", i, sources, err.Error()) - return nil, influxErr(influxdb.EUnprocessableEntity, msg) + return nil, influxErr(errors.EUnprocessableEntity, msg) } rawTemplates = append(rawTemplates, template) } @@ -277,19 +279,19 @@ func (r ReqApply) validActions() (struct { case ActionTypeSkipResource: var asr ActionSkipResource if err := json.Unmarshal(rawAct.Properties, &asr); err != nil { - return actions{}, influxErr(influxdb.EInvalid, unmarshalErrFn(err, i, a)) + return actions{}, influxErr(errors.EInvalid, unmarshalErrFn(err, i, a)) } if err := asr.Kind.OK(); err != nil { - return actions{}, influxErr(influxdb.EInvalid, kindErrFn(err, i, a)) + return actions{}, influxErr(errors.EInvalid, kindErrFn(err, i, a)) } out.SkipResources = append(out.SkipResources, asr) case ActionTypeSkipKind: var ask ActionSkipKind if err := json.Unmarshal(rawAct.Properties, &ask); err != nil { - return actions{}, influxErr(influxdb.EInvalid, unmarshalErrFn(err, i, a)) + return actions{}, influxErr(errors.EInvalid, unmarshalErrFn(err, i, a)) } if err := ask.Kind.OK(); err != nil { - return actions{}, influxErr(influxdb.EInvalid, kindErrFn(err, i, a)) + return actions{}, influxErr(errors.EInvalid, kindErrFn(err, i, a)) } out.SkipKinds = append(out.SkipKinds, ask) default: @@ -297,7 +299,7 @@ func (r ReqApply) validActions() (struct { "invalid action type %q provided for actions[%d] ; Must be one of [%s]", a, i, ActionTypeSkipResource, ) - return actions{}, influxErr(influxdb.EInvalid, msg) + return actions{}, influxErr(errors.EInvalid, msg) } } @@ -322,20 +324,20 @@ func (s *HTTPServerTemplates) apply(w http.ResponseWriter, r *http.Request) { return } - orgID, err := influxdb.IDFromString(reqBody.OrgID) + orgID, err := platform.IDFromString(reqBody.OrgID) if err != nil { - s.api.Err(w, r, &influxdb.Error{ - Code: influxdb.EInvalid, + s.api.Err(w, r, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("invalid organization ID provided: %q", reqBody.OrgID), }) return } - var stackID influxdb.ID + var stackID platform.ID if reqBody.StackID != nil { if err := stackID.DecodeFromString(*reqBody.StackID); err != nil { - s.api.Err(w, r, &influxdb.Error{ - Code: influxdb.EInvalid, + s.api.Err(w, r, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("invalid stack ID provided: %q", *reqBody.StackID), }) return @@ -344,8 +346,8 @@ func (s *HTTPServerTemplates) apply(w http.ResponseWriter, r *http.Request) { parsedTemplate, err := reqBody.Templates(encoding) if err != nil { - s.api.Err(w, r, &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + s.api.Err(w, r, &errors.Error{ + Code: errors.EUnprocessableEntity, Err: err, }) return @@ -405,9 +407,9 @@ func (s *HTTPServerTemplates) apply(w http.ResponseWriter, r *http.Request) { func (s *HTTPServerTemplates) encResp(w http.ResponseWriter, r *http.Request, enc encoder, code int, res interface{}) { w.WriteHeader(code) if err := enc.Encode(res); err != nil { - s.api.Err(w, r, &influxdb.Error{ + s.api.Err(w, r, &errors.Error{ Msg: fmt.Sprintf("unable to marshal; Err: %v", err), - Code: influxdb.EInternal, + Code: errors.EInternal, Err: err, }) } @@ -558,10 +560,10 @@ func convertParseErr(err error) []ValidationErr { return pErr.ValidationErrs() } -func newDecodeErr(encoding string, err error) *influxdb.Error { - return &influxdb.Error{ +func newDecodeErr(encoding string, err error) *errors.Error { + return &errors.Error{ Msg: fmt.Sprintf("unable to unmarshal %s", encoding), - Code: influxdb.EInvalid, + Code: errors.EInvalid, Err: err, } } diff --git a/pkger/http_server_template_test.go b/pkger/http_server_template_test.go index ff7ddd39dc2..2733a211a6b 100644 --- a/pkger/http_server_template_test.go +++ b/pkger/http_server_template_test.go @@ -5,6 +5,7 @@ import ( "context" "encoding/json" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" "io" "io/ioutil" "net/http" @@ -57,7 +58,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { t.Run("create pkg", func(t *testing.T) { t.Run("should successfully return with valid req body", func(t *testing.T) { fakeLabelSVC := mock.NewLabelService() - fakeLabelSVC.FindLabelByIDFn = func(ctx context.Context, id influxdb.ID) (*influxdb.Label, error) { + fakeLabelSVC.FindLabelByIDFn = func(ctx context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ ID: id, }, nil @@ -117,7 +118,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { contentType: "application/json", reqBody: pkger.ReqApply{ DryRun: true, - OrgID: influxdb.ID(9000).String(), + OrgID: platform.ID(9000).String(), RawTemplate: bucketPkgKinds(t, pkger.EncodingJSON), }, }, @@ -125,7 +126,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { name: "defaults json when no content type", reqBody: pkger.ReqApply{ DryRun: true, - OrgID: influxdb.ID(9000).String(), + OrgID: platform.ID(9000).String(), RawTemplate: bucketPkgKinds(t, pkger.EncodingJSON), }, }, @@ -133,7 +134,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { name: "retrieves package from a URL", reqBody: pkger.ReqApply{ DryRun: true, - OrgID: influxdb.ID(9000).String(), + OrgID: platform.ID(9000).String(), Remotes: []pkger.ReqTemplateRemote{{ URL: newPkgURL(t, filesvr.URL, "testdata/remote_bucket.json"), }}, @@ -144,7 +145,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { contentType: "application/x-jsonnet", reqBody: pkger.ReqApply{ DryRun: true, - OrgID: influxdb.ID(9000).String(), + OrgID: platform.ID(9000).String(), RawTemplate: bucketPkgKinds(t, pkger.EncodingJsonnet), }, }, @@ -153,7 +154,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { svc := &fakeSVC{ - dryRunFn: func(ctx context.Context, orgID, userID influxdb.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { + dryRunFn: func(ctx context.Context, orgID, userID platform.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { var opt pkger.ApplyOpt for _, o := range opts { o(&opt) @@ -221,7 +222,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { svc := &fakeSVC{ - dryRunFn: func(ctx context.Context, orgID, userID influxdb.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { + dryRunFn: func(ctx context.Context, orgID, userID platform.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { var opt pkger.ApplyOpt for _, o := range opts { o(&opt) @@ -253,7 +254,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { pkgHandler := pkger.NewHTTPServerTemplates(zap.NewNop(), svc) svr := newMountedHandler(pkgHandler, 1) - body := newReqApplyYMLBody(t, influxdb.ID(9000), true) + body := newReqApplyYMLBody(t, platform.ID(9000), true) testttp. Post(t, "/api/v2/templates/apply", body). @@ -275,7 +276,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { t.Run("all diff and summary resource collections are non null", func(t *testing.T) { svc := &fakeSVC{ - dryRunFn: func(ctx context.Context, orgID, userID influxdb.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { + dryRunFn: func(ctx context.Context, orgID, userID platform.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { // return zero value pkg return pkger.ImpactSummary{}, nil }, @@ -287,7 +288,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { testttp. PostJSON(t, "/api/v2/templates/apply", pkger.ReqApply{ DryRun: true, - OrgID: influxdb.ID(1).String(), + OrgID: platform.ID(1).String(), RawTemplate: bucketPkgKinds(t, pkger.EncodingJSON), }). Headers("Content-Type", "application/json"). @@ -336,7 +337,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { name: "retrieves package from a URL and raw pkgs", reqBody: pkger.ReqApply{ DryRun: true, - OrgID: influxdb.ID(9000).String(), + OrgID: platform.ID(9000).String(), Remotes: []pkger.ReqTemplateRemote{{ ContentType: "json", URL: newPkgURL(t, filesvr.URL, "testdata/remote_bucket.json"), @@ -353,7 +354,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { name: "retrieves packages from raw single and list", reqBody: pkger.ReqApply{ DryRun: true, - OrgID: influxdb.ID(9000).String(), + OrgID: platform.ID(9000).String(), RawTemplate: newBktPkg(t, "bkt4"), RawTemplates: []pkger.ReqRawTemplate{ newBktPkg(t, "bkt1"), @@ -368,7 +369,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { svc := &fakeSVC{ - dryRunFn: func(ctx context.Context, orgID, userID influxdb.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { + dryRunFn: func(ctx context.Context, orgID, userID platform.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { var opt pkger.ApplyOpt for _, o := range opts { o(&opt) @@ -442,7 +443,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { contentType: "application/json", reqBody: pkger.ReqApply{ DryRun: true, - OrgID: influxdb.ID(9000).String(), + OrgID: platform.ID(9000).String(), StackID: strPtr("invalid stack id"), RawTemplate: bucketPkgKinds(t, pkger.EncodingJSON), }, @@ -453,7 +454,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { svc := &fakeSVC{ - dryRunFn: func(ctx context.Context, orgID, userID influxdb.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { + dryRunFn: func(ctx context.Context, orgID, userID platform.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { var opt pkger.ApplyOpt for _, o := range opts { o(&opt) @@ -486,7 +487,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { t.Run("apply a pkg", func(t *testing.T) { t.Run("happy path", func(t *testing.T) { svc := &fakeSVC{ - applyFn: func(ctx context.Context, orgID, userID influxdb.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { + applyFn: func(ctx context.Context, orgID, userID platform.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { var opt pkger.ApplyOpt for _, o := range opts { o(&opt) @@ -523,7 +524,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { testttp. PostJSON(t, "/api/v2/templates/apply", pkger.ReqApply{ - OrgID: influxdb.ID(9000).String(), + OrgID: platform.ID(9000).String(), Secrets: map[string]string{"secret1": "val1"}, RawTemplate: bucketPkgKinds(t, pkger.EncodingJSON), }). @@ -542,7 +543,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { t.Run("all diff and summary resource collections are non null", func(t *testing.T) { svc := &fakeSVC{ - applyFn: func(ctx context.Context, orgID, userID influxdb.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { + applyFn: func(ctx context.Context, orgID, userID platform.ID, opts ...pkger.ApplyOptFn) (pkger.ImpactSummary, error) { // return zero value pkg return pkger.ImpactSummary{}, nil }, @@ -553,7 +554,7 @@ func TestPkgerHTTPServerTemplate(t *testing.T) { testttp. PostJSON(t, "/api/v2/templates/apply", pkger.ReqApply{ - OrgID: influxdb.ID(1).String(), + OrgID: platform.ID(1).String(), RawTemplate: bucketPkgKinds(t, pkger.EncodingJSON), }). Headers("Content-Type", "application/json"). @@ -656,7 +657,7 @@ spec: } } -func newReqApplyYMLBody(t *testing.T, orgID influxdb.ID, dryRun bool) *bytes.Buffer { +func newReqApplyYMLBody(t *testing.T, orgID platform.ID, dryRun bool) *bytes.Buffer { t.Helper() var buf bytes.Buffer @@ -677,13 +678,13 @@ func decodeBody(t *testing.T, r io.Reader, v interface{}) { } } -func newMountedHandler(rh kithttp.ResourceHandler, userID influxdb.ID) chi.Router { +func newMountedHandler(rh kithttp.ResourceHandler, userID platform.ID) chi.Router { r := chi.NewRouter() r.Mount(rh.Prefix(), authMW(userID)(rh)) return r } -func authMW(userID influxdb.ID) func(http.Handler) http.Handler { +func authMW(userID platform.ID) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { r = r.WithContext(pcontext.SetAuthorizer(r.Context(), &influxdb.Session{UserID: userID})) diff --git a/pkger/models.go b/pkger/models.go index 33fe38f8135..2b43159606e 100644 --- a/pkger/models.go +++ b/pkger/models.go @@ -6,6 +6,9 @@ import ( "reflect" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" icheck "github.com/influxdata/influxdb/v2/notification/check" "github.com/influxdata/influxdb/v2/notification/endpoint" @@ -122,18 +125,18 @@ func (k Kind) is(comps ...Kind) bool { // SafeID is an equivalent influxdb.ID that encodes safely with // zero values (influxdb.ID == 0). -type SafeID influxdb.ID +type SafeID platform.ID // Encode will safely encode the id. func (s SafeID) Encode() ([]byte, error) { - id := influxdb.ID(s) + id := platform.ID(s) b, _ := id.Encode() return b, nil } // String prints a encoded string representation of the id. func (s SafeID) String() string { - return influxdb.ID(s).String() + return platform.ID(s).String() } // DiffIdentifier are the identifying fields for any given resource. Each resource @@ -226,7 +229,7 @@ func (d DiffCheckValues) MarshalJSON() ([]byte, error) { // UnmarshalJSON decodes the check values. func (d *DiffCheckValues) UnmarshalJSON(b []byte) (err error) { d.Check, err = icheck.UnmarshalJSON(b) - if influxdb.EInternal == influxdb.ErrorCode(err) { + if errors2.EInternal == errors2.ErrorCode(err) { return nil } return err @@ -340,7 +343,7 @@ func (d DiffNotificationEndpointValues) MarshalJSON() ([]byte, error) { // UnmarshalJSON decodes the notification endpoint. This is necessary unfortunately. func (d *DiffNotificationEndpointValues) UnmarshalJSON(b []byte) (err error) { d.NotificationEndpoint, err = endpoint.UnmarshalJSON(b) - if influxdb.EInvalid == influxdb.ErrorCode(err) { + if errors2.EInvalid == errors2.ErrorCode(err) { return nil } return diff --git a/pkger/parser.go b/pkger/parser.go index 3578ef4e217..365b7ee0be1 100644 --- a/pkger/parser.go +++ b/pkger/parser.go @@ -16,10 +16,11 @@ import ( "strings" "time" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/flux/ast" "github.com/influxdata/flux/ast/edit" "github.com/influxdata/flux/parser" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/pkg/jsonnet" "github.com/influxdata/influxdb/v2/task/options" "gopkg.in/yaml.v3" @@ -104,8 +105,8 @@ func FromFile(filePath string) ReaderFn { return func() (io.Reader, string, error) { u, err := url.Parse(filePath) if err != nil { - return nil, filePath, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, filePath, &errors2.Error{ + Code: errors2.EInvalid, Msg: "invalid filepath provided", Err: err, } @@ -1664,7 +1665,7 @@ func (p *Template) parseChartQueries(dashMetaName string, chartIdx int, resource func (p *Template) parseQuery(prefix, source string, params, task []Resource) (query, error) { files := parser.ParseSource(source).Files if len(files) != 1 { - return query{}, influxErr(influxdb.EInvalid, "invalid query source") + return query{}, influxErr(errors2.EInvalid, "invalid query source") } q := query{ @@ -1756,7 +1757,7 @@ func (p *Template) parseQuery(prefix, source string, params, task []Resource) (q case string: tParams[field].defaultVal, err = time.ParseDuration(defDur) if err != nil { - return query{}, influxErr(influxdb.EInvalid, err.Error()) + return query{}, influxErr(errors2.EInvalid, err.Error()) } case time.Duration: tParams[field].defaultVal = defDur @@ -2287,7 +2288,7 @@ func IsParseErr(err error) bool { return true } - iErr, ok := err.(*influxdb.Error) + iErr, ok := err.(*errors2.Error) if !ok { return false } diff --git a/pkger/parser_test.go b/pkger/parser_test.go index 83a2ef288ba..fec7d8aeb6f 100644 --- a/pkger/parser_test.go +++ b/pkger/parser_test.go @@ -13,6 +13,8 @@ import ( "testing" "time" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/notification" icheck "github.com/influxdata/influxdb/v2/notification/check" @@ -4561,17 +4563,17 @@ func Test_IsParseError(t *testing.T) { }, { name: "wrapped by influxdb error", - err: &influxdb.Error{ + err: &errors2.Error{ Err: &parseErr{}, }, expected: true, }, { name: "deeply nested in influxdb error", - err: &influxdb.Error{ - Err: &influxdb.Error{ - Err: &influxdb.Error{ - Err: &influxdb.Error{ + err: &errors2.Error{ + Err: &errors2.Error{ + Err: &errors2.Error{ + Err: &errors2.Error{ Err: &parseErr{}, }, }, @@ -4581,7 +4583,7 @@ func Test_IsParseError(t *testing.T) { }, { name: "influxdb error without nested parse err", - err: &influxdb.Error{ + err: &errors2.Error{ Err: errors.New("nope"), }, expected: false, diff --git a/pkger/service.go b/pkger/service.go index e5027d22589..4395cbdee42 100644 --- a/pkger/service.go +++ b/pkger/service.go @@ -12,6 +12,9 @@ import ( "sync" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-stack/stack" "github.com/influxdata/influxdb/v2" ierrors "github.com/influxdata/influxdb/v2/kit/errors" @@ -32,8 +35,8 @@ const APIVersion2 = "influxdata.com/v2alpha2" // platform. This stack is updated only after side effects of applying a template. // If the template is applied, and no changes are had, then the stack is not updated. type Stack struct { - ID influxdb.ID - OrgID influxdb.ID + ID platform.ID + OrgID platform.ID CreatedAt time.Time `json:"createdAt"` Events []StackEvent } @@ -60,7 +63,7 @@ type ( } StackCreate struct { - OrgID influxdb.ID + OrgID platform.ID Name string Description string Sources []string @@ -72,7 +75,7 @@ type ( // applying a template. StackResource struct { APIVersion string - ID influxdb.ID + ID platform.ID Name string Kind Kind MetaName string @@ -87,7 +90,7 @@ type ( // StackUpdate provides a means to update an existing stack. StackUpdate struct { - ID influxdb.ID + ID platform.ID Name *string Description *string TemplateURLs []string @@ -96,7 +99,7 @@ type ( StackAdditionalResource struct { APIVersion string - ID influxdb.ID + ID platform.ID Kind Kind MetaName string } @@ -127,16 +130,16 @@ const ResourceTypeStack influxdb.ResourceType = "stack" // SVC is the packages service interface. type SVC interface { - InitStack(ctx context.Context, userID influxdb.ID, stack StackCreate) (Stack, error) - UninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) (Stack, error) - DeleteStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) error - ListStacks(ctx context.Context, orgID influxdb.ID, filter ListFilter) ([]Stack, error) - ReadStack(ctx context.Context, id influxdb.ID) (Stack, error) + InitStack(ctx context.Context, userID platform.ID, stack StackCreate) (Stack, error) + UninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) (Stack, error) + DeleteStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) error + ListStacks(ctx context.Context, orgID platform.ID, filter ListFilter) ([]Stack, error) + ReadStack(ctx context.Context, id platform.ID) (Stack, error) UpdateStack(ctx context.Context, upd StackUpdate) (Stack, error) Export(ctx context.Context, opts ...ExportOptFn) (*Template, error) - DryRun(ctx context.Context, orgID, userID influxdb.ID, opts ...ApplyOptFn) (ImpactSummary, error) - Apply(ctx context.Context, orgID, userID influxdb.ID, opts ...ApplyOptFn) (ImpactSummary, error) + DryRun(ctx context.Context, orgID, userID platform.ID, opts ...ApplyOptFn) (ImpactSummary, error) + Apply(ctx context.Context, orgID, userID platform.ID, opts ...ApplyOptFn) (ImpactSummary, error) } // SVCMiddleware is a service middleware func. @@ -146,7 +149,7 @@ type serviceOpt struct { logger *zap.Logger applyReqLimit int - idGen influxdb.IDGenerator + idGen platform.IDGenerator nameGen NameGenerator timeGen influxdb.TimeGenerator store Store @@ -175,7 +178,7 @@ func WithLogger(log *zap.Logger) ServiceSetterFn { } // WithIDGenerator sets the id generator for the service. -func WithIDGenerator(idGen influxdb.IDGenerator) ServiceSetterFn { +func WithIDGenerator(idGen platform.IDGenerator) ServiceSetterFn { return func(opt *serviceOpt) { opt.idGen = idGen } @@ -281,10 +284,10 @@ func WithVariableSVC(varSVC influxdb.VariableService) ServiceSetterFn { // Store is the storage behavior the Service depends on. type Store interface { CreateStack(ctx context.Context, stack Stack) error - ListStacks(ctx context.Context, orgID influxdb.ID, filter ListFilter) ([]Stack, error) - ReadStackByID(ctx context.Context, id influxdb.ID) (Stack, error) + ListStacks(ctx context.Context, orgID platform.ID, filter ListFilter) ([]Stack, error) + ReadStackByID(ctx context.Context, id platform.ID) (Stack, error) UpdateStack(ctx context.Context, stack Stack) error - DeleteStack(ctx context.Context, id influxdb.ID) error + DeleteStack(ctx context.Context, id platform.ID) error } // Service provides the template business logic including all the dependencies to make @@ -294,7 +297,7 @@ type Service struct { // internal dependencies applyReqLimit int - idGen influxdb.IDGenerator + idGen platform.IDGenerator nameGen NameGenerator store Store timeGen influxdb.TimeGenerator @@ -354,15 +357,15 @@ func NewService(opts ...ServiceSetterFn) *Service { // InitStack will create a new stack for the given user and its given org. The stack can be created // with urls that point to the location of packages that are included as part of the stack when // it is applied. -func (s *Service) InitStack(ctx context.Context, userID influxdb.ID, stCreate StackCreate) (Stack, error) { +func (s *Service) InitStack(ctx context.Context, userID platform.ID, stCreate StackCreate) (Stack, error) { if err := validURLs(stCreate.TemplateURLs); err != nil { return Stack{}, err } if _, err := s.orgSVC.FindOrganizationByID(ctx, stCreate.OrgID); err != nil { - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors2.ErrorCode(err) == errors2.ENotFound { msg := fmt.Sprintf("organization dependency does not exist for id[%q]", stCreate.OrgID.String()) - return Stack{}, influxErr(influxdb.EConflict, msg) + return Stack{}, influxErr(errors2.EConflict, msg) } return Stack{}, internalErr(err) } @@ -391,7 +394,7 @@ func (s *Service) InitStack(ctx context.Context, userID influxdb.ID, stCreate St } // UninstallStack will remove all resources associated with the stack. -func (s *Service) UninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) (Stack, error) { +func (s *Service) UninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) (Stack, error) { uninstalledStack, err := s.uninstallStack(ctx, identifiers) if err != nil { return Stack{}, err @@ -410,9 +413,9 @@ func (s *Service) UninstallStack(ctx context.Context, identifiers struct{ OrgID, } // DeleteStack removes a stack and all the resources that have are associated with the stack. -func (s *Service) DeleteStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) (e error) { +func (s *Service) DeleteStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) (e error) { deletedStack, err := s.uninstallStack(ctx, identifiers) - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors2.ErrorCode(err) == errors2.ENotFound { return nil } if err != nil { @@ -422,14 +425,14 @@ func (s *Service) DeleteStack(ctx context.Context, identifiers struct{ OrgID, Us return s.store.DeleteStack(ctx, deletedStack.ID) } -func (s *Service) uninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) (_ Stack, e error) { +func (s *Service) uninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) (_ Stack, e error) { stack, err := s.store.ReadStackByID(ctx, identifiers.StackID) if err != nil { return Stack{}, err } if stack.OrgID != identifiers.OrgID { - return Stack{}, &influxdb.Error{ - Code: influxdb.EConflict, + return Stack{}, &errors2.Error{ + Code: errors2.EConflict, Msg: "you do not have access to given stack ID", } } @@ -452,17 +455,17 @@ func (s *Service) uninstallStack(ctx context.Context, identifiers struct{ OrgID, // ListFilter are filter options for filtering stacks from being returned. type ListFilter struct { - StackIDs []influxdb.ID + StackIDs []platform.ID Names []string } // ListStacks returns a list of stacks. -func (s *Service) ListStacks(ctx context.Context, orgID influxdb.ID, f ListFilter) ([]Stack, error) { +func (s *Service) ListStacks(ctx context.Context, orgID platform.ID, f ListFilter) ([]Stack, error) { return s.store.ListStacks(ctx, orgID, f) } // ReadStack returns a stack that matches the given id. -func (s *Service) ReadStack(ctx context.Context, id influxdb.ID) (Stack, error) { +func (s *Service) ReadStack(ctx context.Context, id platform.ID) (Stack, error) { return s.store.ReadStackByID(ctx, id) } @@ -497,7 +500,7 @@ func (s *Service) applyStackUpdate(existing Stack, upd StackUpdate) Stack { type key struct { k Kind - id influxdb.ID + id platform.ID } mExistingResources := make(map[key]bool) mExistingNames := make(map[string]bool) @@ -551,7 +554,7 @@ type ( // ExportOpt are the options for creating a new package. ExportOpt struct { - StackID influxdb.ID + StackID platform.ID OrgIDs []ExportByOrgIDOpt Resources []ResourceToClone } @@ -559,7 +562,7 @@ type ( // ExportByOrgIDOpt identifies an org to export resources for and provides // multiple filtering options. ExportByOrgIDOpt struct { - OrgID influxdb.ID + OrgID platform.ID LabelNames []string ResourceKinds []Kind } @@ -596,7 +599,7 @@ func ExportWithAllOrgResources(orgIDOpt ExportByOrgIDOpt) ExportOptFn { } // ExportWithStackID provides an export for the given stack ID. -func ExportWithStackID(stackID influxdb.ID) ExportOptFn { +func ExportWithStackID(stackID platform.ID) ExportOptFn { return func(opt *ExportOpt) error { opt.StackID = stackID return nil @@ -668,7 +671,7 @@ func (s *Service) Export(ctx context.Context, setters ...ExportOptFn) (*Template return template, nil } -func (s *Service) cloneOrgResources(ctx context.Context, orgID influxdb.ID, resourceKinds []Kind) ([]ResourceToClone, error) { +func (s *Service) cloneOrgResources(ctx context.Context, orgID platform.ID, resourceKinds []Kind) ([]ResourceToClone, error) { var resources []ResourceToClone for _, resGen := range s.filterOrgResourceKinds(resourceKinds) { existingResources, err := resGen.cloneFn(ctx, orgID) @@ -681,7 +684,7 @@ func (s *Service) cloneOrgResources(ctx context.Context, orgID influxdb.ID, reso return resources, nil } -func (s *Service) cloneOrgBuckets(ctx context.Context, orgID influxdb.ID) ([]ResourceToClone, error) { +func (s *Service) cloneOrgBuckets(ctx context.Context, orgID platform.ID) ([]ResourceToClone, error) { buckets, _, err := s.bucketSVC.FindBuckets(ctx, influxdb.BucketFilter{ OrganizationID: &orgID, }) @@ -703,7 +706,7 @@ func (s *Service) cloneOrgBuckets(ctx context.Context, orgID influxdb.ID) ([]Res return resources, nil } -func (s *Service) cloneOrgChecks(ctx context.Context, orgID influxdb.ID) ([]ResourceToClone, error) { +func (s *Service) cloneOrgChecks(ctx context.Context, orgID platform.ID) ([]ResourceToClone, error) { checks, _, err := s.checkSVC.FindChecks(ctx, influxdb.CheckFilter{ OrgID: &orgID, }) @@ -722,7 +725,7 @@ func (s *Service) cloneOrgChecks(ctx context.Context, orgID influxdb.ID) ([]Reso return resources, nil } -func (s *Service) cloneOrgDashboards(ctx context.Context, orgID influxdb.ID) ([]ResourceToClone, error) { +func (s *Service) cloneOrgDashboards(ctx context.Context, orgID platform.ID) ([]ResourceToClone, error) { dashs, _, err := s.dashSVC.FindDashboards(ctx, influxdb.DashboardFilter{ OrganizationID: &orgID, }, influxdb.FindOptions{Limit: 100}) @@ -740,7 +743,7 @@ func (s *Service) cloneOrgDashboards(ctx context.Context, orgID influxdb.ID) ([] return resources, nil } -func (s *Service) cloneOrgLabels(ctx context.Context, orgID influxdb.ID) ([]ResourceToClone, error) { +func (s *Service) cloneOrgLabels(ctx context.Context, orgID platform.ID) ([]ResourceToClone, error) { filter := influxdb.LabelFilter{ OrgID: &orgID, } @@ -761,7 +764,7 @@ func (s *Service) cloneOrgLabels(ctx context.Context, orgID influxdb.ID) ([]Reso return resources, nil } -func (s *Service) cloneOrgNotificationEndpoints(ctx context.Context, orgID influxdb.ID) ([]ResourceToClone, error) { +func (s *Service) cloneOrgNotificationEndpoints(ctx context.Context, orgID platform.ID) ([]ResourceToClone, error) { endpoints, _, err := s.endpointSVC.FindNotificationEndpoints(ctx, influxdb.NotificationEndpointFilter{ OrgID: &orgID, }) @@ -780,7 +783,7 @@ func (s *Service) cloneOrgNotificationEndpoints(ctx context.Context, orgID influ return resources, nil } -func (s *Service) cloneOrgNotificationRules(ctx context.Context, orgID influxdb.ID) ([]ResourceToClone, error) { +func (s *Service) cloneOrgNotificationRules(ctx context.Context, orgID platform.ID) ([]ResourceToClone, error) { rules, _, err := s.ruleSVC.FindNotificationRules(ctx, influxdb.NotificationRuleFilter{ OrgID: &orgID, }) @@ -799,7 +802,7 @@ func (s *Service) cloneOrgNotificationRules(ctx context.Context, orgID influxdb. return resources, nil } -func (s *Service) cloneOrgTasks(ctx context.Context, orgID influxdb.ID) ([]ResourceToClone, error) { +func (s *Service) cloneOrgTasks(ctx context.Context, orgID platform.ID) ([]ResourceToClone, error) { tasks, err := s.getAllTasks(ctx, orgID) if err != nil { return nil, err @@ -819,7 +822,7 @@ func (s *Service) cloneOrgTasks(ctx context.Context, orgID influxdb.ID) ([]Resou return nil, err } - mTasks := make(map[influxdb.ID]*influxdb.Task) + mTasks := make(map[platform.ID]*influxdb.Task) for i := range tasks { t := tasks[i] if t.Type != influxdb.TaskSystemType { @@ -844,7 +847,7 @@ func (s *Service) cloneOrgTasks(ctx context.Context, orgID influxdb.ID) ([]Resou return resources, nil } -func (s *Service) cloneOrgTelegrafs(ctx context.Context, orgID influxdb.ID) ([]ResourceToClone, error) { +func (s *Service) cloneOrgTelegrafs(ctx context.Context, orgID platform.ID) ([]ResourceToClone, error) { teles, _, err := s.teleSVC.FindTelegrafConfigs(ctx, influxdb.TelegrafConfigFilter{OrgID: &orgID}) if err != nil { return nil, err @@ -860,7 +863,7 @@ func (s *Service) cloneOrgTelegrafs(ctx context.Context, orgID influxdb.ID) ([]R return resources, nil } -func (s *Service) cloneOrgVariables(ctx context.Context, orgID influxdb.ID) ([]ResourceToClone, error) { +func (s *Service) cloneOrgVariables(ctx context.Context, orgID platform.ID) ([]ResourceToClone, error) { vars, err := s.varSVC.FindVariables(ctx, influxdb.VariableFilter{ OrganizationID: &orgID, }, influxdb.FindOptions{Limit: 10000}) @@ -880,7 +883,7 @@ func (s *Service) cloneOrgVariables(ctx context.Context, orgID influxdb.ID) ([]R } type ( - cloneResFn func(context.Context, influxdb.ID) ([]ResourceToClone, error) + cloneResFn func(context.Context, platform.ID) ([]ResourceToClone, error) resClone struct { resType influxdb.ResourceType cloneFn cloneResFn @@ -931,7 +934,7 @@ func (s *Service) filterOrgResourceKinds(resourceKindFilters []Kind) []resClone // ImpactSummary represents the impact the application of a template will have on the system. type ImpactSummary struct { Sources []string - StackID influxdb.ID + StackID platform.ID Diff Diff Summary Summary } @@ -957,7 +960,7 @@ func (i *ImpactSummary) communityName() string { // DryRun provides a dry run of the template application. The template will be marked verified // for later calls to Apply. This func will be run on an Apply if it has not been run // already. -func (s *Service) DryRun(ctx context.Context, orgID, userID influxdb.ID, opts ...ApplyOptFn) (ImpactSummary, error) { +func (s *Service) DryRun(ctx context.Context, orgID, userID platform.ID, opts ...ApplyOptFn) (ImpactSummary, error) { opt := applyOptFromOptFns(opts...) template, err := s.templateFromApplyOpts(ctx, opt) if err != nil { @@ -977,7 +980,7 @@ func (s *Service) DryRun(ctx context.Context, orgID, userID influxdb.ID, opts .. }, nil } -func (s *Service) dryRun(ctx context.Context, orgID influxdb.ID, template *Template, opt ApplyOpt) (*stateCoordinator, error) { +func (s *Service) dryRun(ctx context.Context, orgID platform.ID, template *Template, opt ApplyOpt) (*stateCoordinator, error) { // so here's the deal, when we have issues with the parsing validation, we // continue to do the diff anyhow. any resource that does not have a name // will be skipped, and won't bleed into the dry run here. We can now return @@ -1039,7 +1042,7 @@ func (s *Service) dryRun(ctx context.Context, orgID influxdb.ID, template *Templ return state, parseErr } -func (s *Service) dryRunBuckets(ctx context.Context, orgID influxdb.ID, bkts map[string]*stateBucket) { +func (s *Service) dryRunBuckets(ctx context.Context, orgID platform.ID, bkts map[string]*stateBucket) { for _, stateBkt := range bkts { stateBkt.orgID = orgID var existing *influxdb.Bucket @@ -1055,7 +1058,7 @@ func (s *Service) dryRunBuckets(ctx context.Context, orgID influxdb.ID, bkts map } } -func (s *Service) dryRunChecks(ctx context.Context, orgID influxdb.ID, checks map[string]*stateCheck) { +func (s *Service) dryRunChecks(ctx context.Context, orgID platform.ID, checks map[string]*stateCheck) { for _, c := range checks { c.orgID = orgID @@ -1076,7 +1079,7 @@ func (s *Service) dryRunChecks(ctx context.Context, orgID influxdb.ID, checks ma } } -func (s *Service) dryRunDashboards(ctx context.Context, orgID influxdb.ID, dashs map[string]*stateDashboard) { +func (s *Service) dryRunDashboards(ctx context.Context, orgID platform.ID, dashs map[string]*stateDashboard) { for _, stateDash := range dashs { stateDash.orgID = orgID var existing *influxdb.Dashboard @@ -1090,7 +1093,7 @@ func (s *Service) dryRunDashboards(ctx context.Context, orgID influxdb.ID, dashs } } -func (s *Service) dryRunLabels(ctx context.Context, orgID influxdb.ID, labels map[string]*stateLabel) { +func (s *Service) dryRunLabels(ctx context.Context, orgID platform.ID, labels map[string]*stateLabel) { for _, l := range labels { l.orgID = orgID existingLabel, _ := s.findLabel(ctx, orgID, l) @@ -1101,7 +1104,7 @@ func (s *Service) dryRunLabels(ctx context.Context, orgID influxdb.ID, labels ma } } -func (s *Service) dryRunNotificationEndpoints(ctx context.Context, orgID influxdb.ID, endpoints map[string]*stateEndpoint) error { +func (s *Service) dryRunNotificationEndpoints(ctx context.Context, orgID platform.ID, endpoints map[string]*stateEndpoint) error { existingEndpoints, _, err := s.endpointSVC.FindNotificationEndpoints(ctx, influxdb.NotificationEndpointFilter{ OrgID: &orgID, }) // grab em all @@ -1110,7 +1113,7 @@ func (s *Service) dryRunNotificationEndpoints(ctx context.Context, orgID influxd } mExistingByName := make(map[string]influxdb.NotificationEndpoint) - mExistingByID := make(map[influxdb.ID]influxdb.NotificationEndpoint) + mExistingByID := make(map[platform.ID]influxdb.NotificationEndpoint) for i := range existingEndpoints { e := existingEndpoints[i] mExistingByName[e.GetName()] = e @@ -1138,7 +1141,7 @@ func (s *Service) dryRunNotificationEndpoints(ctx context.Context, orgID influxd return nil } -func (s *Service) dryRunNotificationRules(ctx context.Context, orgID influxdb.ID, rules map[string]*stateRule, endpoints map[string]*stateEndpoint) error { +func (s *Service) dryRunNotificationRules(ctx context.Context, orgID platform.ID, rules map[string]*stateRule, endpoints map[string]*stateEndpoint) error { for _, rule := range rules { rule.orgID = orgID var existing influxdb.NotificationRule @@ -1156,8 +1159,8 @@ func (s *Service) dryRunNotificationRules(ctx context.Context, orgID influxdb.ID e, ok := endpoints[r.parserRule.endpointMetaName()] if !IsRemoval(r.stateStatus) && !ok { err := fmt.Errorf("failed to find notification endpoint %q dependency for notification rule %q", r.parserRule.endpointName, r.parserRule.MetaName()) - return &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + return &errors2.Error{ + Code: errors2.EUnprocessableEntity, Err: err, } } @@ -1167,7 +1170,7 @@ func (s *Service) dryRunNotificationRules(ctx context.Context, orgID influxdb.ID return nil } -func (s *Service) dryRunSecrets(ctx context.Context, orgID influxdb.ID, template *Template) error { +func (s *Service) dryRunSecrets(ctx context.Context, orgID platform.ID, template *Template) error { templateSecrets := template.mSecrets if len(templateSecrets) == 0 { return nil @@ -1175,7 +1178,7 @@ func (s *Service) dryRunSecrets(ctx context.Context, orgID influxdb.ID, template existingSecrets, err := s.secretSVC.GetSecretKeys(ctx, orgID) if err != nil { - return &influxdb.Error{Code: influxdb.EInternal, Err: err} + return &errors2.Error{Code: errors2.EInternal, Err: err} } for _, secret := range existingSecrets { @@ -1185,7 +1188,7 @@ func (s *Service) dryRunSecrets(ctx context.Context, orgID influxdb.ID, template return nil } -func (s *Service) dryRunTasks(ctx context.Context, orgID influxdb.ID, tasks map[string]*stateTask) { +func (s *Service) dryRunTasks(ctx context.Context, orgID platform.ID, tasks map[string]*stateTask) { for _, stateTask := range tasks { stateTask.orgID = orgID var existing *influxdb.Task @@ -1199,7 +1202,7 @@ func (s *Service) dryRunTasks(ctx context.Context, orgID influxdb.ID, tasks map[ } } -func (s *Service) dryRunTelegrafConfigs(ctx context.Context, orgID influxdb.ID, teleConfigs map[string]*stateTelegraf) { +func (s *Service) dryRunTelegrafConfigs(ctx context.Context, orgID platform.ID, teleConfigs map[string]*stateTelegraf) { for _, stateTele := range teleConfigs { stateTele.orgID = orgID var existing *influxdb.TelegrafConfig @@ -1213,10 +1216,10 @@ func (s *Service) dryRunTelegrafConfigs(ctx context.Context, orgID influxdb.ID, } } -func (s *Service) dryRunVariables(ctx context.Context, orgID influxdb.ID, vars map[string]*stateVariable) { +func (s *Service) dryRunVariables(ctx context.Context, orgID platform.ID, vars map[string]*stateVariable) { existingVars, _ := s.getAllPlatformVariables(ctx, orgID) - mIDs := make(map[influxdb.ID]*influxdb.Variable) + mIDs := make(map[platform.ID]*influxdb.Variable) mNames := make(map[string]*influxdb.Variable) for _, v := range existingVars { mIDs[v.ID] = v @@ -1360,7 +1363,7 @@ func (s *Service) dryRunResourceLabelMapping(ctx context.Context, state *stateCo ResourceID: ident.id, ResourceType: ident.resourceType, }) - if err != nil && influxdb.ErrorCode(err) != influxdb.ENotFound { + if err != nil && errors2.ErrorCode(err) != errors2.ENotFound { msgFmt := fmt.Sprintf("failed to find labels mappings for %s resource[%q]", ident.resourceType, ident.id) return nil, ierrors.Wrap(err, msgFmt) } @@ -1395,7 +1398,7 @@ func (s *Service) dryRunResourceLabelMapping(ctx context.Context, state *stateCo return mappings, nil } -func (s *Service) addStackState(ctx context.Context, stackID influxdb.ID, state *stateCoordinator) error { +func (s *Service) addStackState(ctx context.Context, stackID platform.ID, state *stateCoordinator) error { stack, err := s.store.ReadStackByID(ctx, stackID) if err != nil { return ierrors.Wrap(err, "reading stack") @@ -1411,7 +1414,7 @@ type ( Templates []*Template EnvRefs map[string]interface{} MissingSecrets map[string]string - StackID influxdb.ID + StackID platform.ID ResourcesToSkip map[ActionSkipResource]bool KindsToSkip map[Kind]bool } @@ -1491,7 +1494,7 @@ func ApplyWithSecrets(secrets map[string]string) ApplyOptFn { } // ApplyWithStackID associates the application of a template with a stack. -func ApplyWithStackID(stackID influxdb.ID) ApplyOptFn { +func ApplyWithStackID(stackID platform.ID) ApplyOptFn { return func(o *ApplyOpt) { o.StackID = stackID } @@ -1508,7 +1511,7 @@ func applyOptFromOptFns(opts ...ApplyOptFn) ApplyOpt { // Apply will apply all the resources identified in the provided template. The entire template will be applied // in its entirety. If a failure happens midway then the entire template will be rolled back to the state // from before the template were applied. -func (s *Service) Apply(ctx context.Context, orgID, userID influxdb.ID, opts ...ApplyOptFn) (impact ImpactSummary, e error) { +func (s *Service) Apply(ctx context.Context, orgID, userID platform.ID, opts ...ApplyOptFn) (impact ImpactSummary, e error) { opt := applyOptFromOptFns(opts...) template, err := s.templateFromApplyOpts(ctx, opt) @@ -1539,7 +1542,7 @@ func (s *Service) Apply(ctx context.Context, orgID, userID influxdb.ID, opts ... stackID = newStack.ID } - defer func(stackID influxdb.ID) { + defer func(stackID platform.ID) { updateStackFn := s.updateStackAfterSuccess if e != nil { updateStackFn = s.updateStackAfterRollback @@ -1574,7 +1577,7 @@ func (s *Service) Apply(ctx context.Context, orgID, userID influxdb.ID, opts ... }, nil } -func (s *Service) applyState(ctx context.Context, coordinator *rollbackCoordinator, orgID, userID influxdb.ID, state *stateCoordinator, missingSecrets map[string]string) (e error) { +func (s *Service) applyState(ctx context.Context, coordinator *rollbackCoordinator, orgID, userID platform.ID, state *stateCoordinator, missingSecrets map[string]string) (e error) { endpointApp, ruleApp, err := s.applyNotificationGenerator(ctx, userID, state.rules(), state.endpoints()) if err != nil { return ierrors.Wrap(err, "failed to setup notification generator") @@ -1642,7 +1645,7 @@ func (s *Service) applyBuckets(ctx context.Context, buckets []*stateBucket) appl mutex := new(doMutex) rollbackBuckets := make([]*stateBucket, 0, len(buckets)) - createFn := func(ctx context.Context, i int, orgID, userID influxdb.ID) *applyErrBody { + createFn := func(ctx context.Context, i int, orgID, userID platform.ID) *applyErrBody { var b *stateBucket mutex.Do(func() { buckets[i].orgID = orgID @@ -1675,7 +1678,7 @@ func (s *Service) applyBuckets(ctx context.Context, buckets []*stateBucket) appl }, rollbacker: rollbacker{ resource: resource, - fn: func(_ influxdb.ID) error { return s.rollbackBuckets(ctx, rollbackBuckets) }, + fn: func(_ platform.ID) error { return s.rollbackBuckets(ctx, rollbackBuckets) }, }, } } @@ -1724,7 +1727,7 @@ func (s *Service) applyBucket(ctx context.Context, b *stateBucket) (influxdb.Buc switch { case IsRemoval(b.stateStatus): if err := s.bucketSVC.DeleteBucket(ctx, b.ID()); err != nil { - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors2.ErrorCode(err) == errors2.ENotFound { return influxdb.Bucket{}, nil } return influxdb.Bucket{}, applyFailErr("delete", b.stateIdentity(), err) @@ -1764,7 +1767,7 @@ func (s *Service) applyChecks(ctx context.Context, checks []*stateCheck) applier mutex := new(doMutex) rollbackChecks := make([]*stateCheck, 0, len(checks)) - createFn := func(ctx context.Context, i int, orgID, userID influxdb.ID) *applyErrBody { + createFn := func(ctx context.Context, i int, orgID, userID platform.ID) *applyErrBody { var c *stateCheck mutex.Do(func() { checks[i].orgID = orgID @@ -1794,7 +1797,7 @@ func (s *Service) applyChecks(ctx context.Context, checks []*stateCheck) applier }, rollbacker: rollbacker{ resource: resource, - fn: func(_ influxdb.ID) error { return s.rollbackChecks(ctx, rollbackChecks) }, + fn: func(_ platform.ID) error { return s.rollbackChecks(ctx, rollbackChecks) }, }, } } @@ -1841,11 +1844,11 @@ func (s *Service) rollbackChecks(ctx context.Context, checks []*stateCheck) erro return nil } -func (s *Service) applyCheck(ctx context.Context, c *stateCheck, userID influxdb.ID) (influxdb.Check, error) { +func (s *Service) applyCheck(ctx context.Context, c *stateCheck, userID platform.ID) (influxdb.Check, error) { switch { case IsRemoval(c.stateStatus): if err := s.checkSVC.DeleteCheck(ctx, c.ID()); err != nil { - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors2.ErrorCode(err) == errors2.ENotFound { return &icheck.Threshold{Base: icheck.Base{ID: c.ID()}}, nil } return nil, applyFailErr("delete", c.stateIdentity(), err) @@ -1879,7 +1882,7 @@ func (s *Service) applyDashboards(ctx context.Context, dashboards []*stateDashbo mutex := new(doMutex) rollbackDashboards := make([]*stateDashboard, 0, len(dashboards)) - createFn := func(ctx context.Context, i int, orgID, userID influxdb.ID) *applyErrBody { + createFn := func(ctx context.Context, i int, orgID, userID platform.ID) *applyErrBody { var d *stateDashboard mutex.Do(func() { dashboards[i].orgID = orgID @@ -1908,7 +1911,7 @@ func (s *Service) applyDashboards(ctx context.Context, dashboards []*stateDashbo }, rollbacker: rollbacker{ resource: resource, - fn: func(_ influxdb.ID) error { + fn: func(_ platform.ID) error { return s.rollbackDashboards(ctx, rollbackDashboards) }, }, @@ -1919,7 +1922,7 @@ func (s *Service) applyDashboard(ctx context.Context, d *stateDashboard) (influx switch { case IsRemoval(d.stateStatus): if err := s.dashSVC.DeleteDashboard(ctx, d.ID()); err != nil { - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors2.ErrorCode(err) == errors2.ENotFound { return influxdb.Dashboard{}, nil } return influxdb.Dashboard{}, applyFailErr("delete", d.stateIdentity(), err) @@ -2017,7 +2020,7 @@ func (s *Service) applyLabels(ctx context.Context, labels []*stateLabel) applier mutex := new(doMutex) rollBackLabels := make([]*stateLabel, 0, len(labels)) - createFn := func(ctx context.Context, i int, orgID, userID influxdb.ID) *applyErrBody { + createFn := func(ctx context.Context, i int, orgID, userID platform.ID) *applyErrBody { var l *stateLabel mutex.Do(func() { labels[i].orgID = orgID @@ -2050,7 +2053,7 @@ func (s *Service) applyLabels(ctx context.Context, labels []*stateLabel) applier }, rollbacker: rollbacker{ resource: resource, - fn: func(_ influxdb.ID) error { return s.rollbackLabels(ctx, rollBackLabels) }, + fn: func(_ platform.ID) error { return s.rollbackLabels(ctx, rollBackLabels) }, }, } } @@ -2109,7 +2112,7 @@ func (s *Service) applyLabel(ctx context.Context, l *stateLabel) (influxdb.Label influxLabel = &creatLabel err = ierrors.Wrap(s.labelSVC.CreateLabel(ctx, &creatLabel), "creating") } - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors2.ErrorCode(err) == errors2.ENotFound { return influxdb.Label{}, nil } if err != nil || influxLabel == nil { @@ -2119,11 +2122,11 @@ func (s *Service) applyLabel(ctx context.Context, l *stateLabel) (influxdb.Label return *influxLabel, nil } -func (s *Service) applyNotificationEndpoints(ctx context.Context, userID influxdb.ID, endpoints []*stateEndpoint) (applier, func(influxdb.ID) error) { +func (s *Service) applyNotificationEndpoints(ctx context.Context, userID platform.ID, endpoints []*stateEndpoint) (applier, func(platform.ID) error) { mutex := new(doMutex) rollbackEndpoints := make([]*stateEndpoint, 0, len(endpoints)) - createFn := func(ctx context.Context, i int, orgID, userID influxdb.ID) *applyErrBody { + createFn := func(ctx context.Context, i int, orgID, userID platform.ID) *applyErrBody { var endpoint *stateEndpoint mutex.Do(func() { endpoints[i].orgID = orgID @@ -2172,7 +2175,7 @@ func (s *Service) applyNotificationEndpoints(ctx context.Context, userID influxd return nil } - rollbackFn := func(_ influxdb.ID) error { + rollbackFn := func(_ platform.ID) error { return s.rollbackNotificationEndpoints(ctx, userID, rollbackEndpoints) } @@ -2182,18 +2185,18 @@ func (s *Service) applyNotificationEndpoints(ctx context.Context, userID influxd fn: createFn, }, rollbacker: rollbacker{ - fn: func(_ influxdb.ID) error { + fn: func(_ platform.ID) error { return nil }, }, }, rollbackFn } -func (s *Service) applyNotificationEndpoint(ctx context.Context, e *stateEndpoint, userID influxdb.ID) (influxdb.NotificationEndpoint, error) { +func (s *Service) applyNotificationEndpoint(ctx context.Context, e *stateEndpoint, userID platform.ID) (influxdb.NotificationEndpoint, error) { switch { case IsRemoval(e.stateStatus): _, _, err := s.endpointSVC.DeleteNotificationEndpoint(ctx, e.ID()) - if err != nil && influxdb.ErrorCode(err) != influxdb.ENotFound { + if err != nil && errors2.ErrorCode(err) != errors2.ENotFound { return nil, applyFailErr("delete", e.stateIdentity(), err) } return e.existing, nil @@ -2218,7 +2221,7 @@ func (s *Service) applyNotificationEndpoint(ctx context.Context, e *stateEndpoin } } -func (s *Service) rollbackNotificationEndpoints(ctx context.Context, userID influxdb.ID, endpoints []*stateEndpoint) error { +func (s *Service) rollbackNotificationEndpoints(ctx context.Context, userID platform.ID, endpoints []*stateEndpoint) error { rollbackFn := func(e *stateEndpoint) error { if !IsNew(e.stateStatus) && e.existing == nil { return nil @@ -2252,7 +2255,7 @@ func (s *Service) rollbackNotificationEndpoints(ctx context.Context, userID infl return nil } -func (s *Service) applyNotificationGenerator(ctx context.Context, userID influxdb.ID, rules []*stateRule, stateEndpoints []*stateEndpoint) (endpointApplier applier, ruleApplier applier, err error) { +func (s *Service) applyNotificationGenerator(ctx context.Context, userID platform.ID, rules []*stateRule, stateEndpoints []*stateEndpoint) (endpointApplier applier, ruleApplier applier, err error) { mEndpoints := make(map[string]*stateEndpoint) for _, e := range stateEndpoints { mEndpoints[e.parserEndpoint.MetaName()] = e @@ -2287,7 +2290,7 @@ func (s *Service) applyNotificationGenerator(ctx context.Context, userID influxd // reference for the rule has settled. The dependency has to be available before rolling back // notification rules. endpointApp.rollbacker = rollbacker{ - fn: func(orgID influxdb.ID) error { + fn: func(orgID platform.ID) error { if err := endpointRollbackFn(orgID); err != nil { s.log.Error("failed to roll back endpoints", zap.Error(err)) } @@ -2298,11 +2301,11 @@ func (s *Service) applyNotificationGenerator(ctx context.Context, userID influxd return endpointApp, ruleApp, nil } -func (s *Service) applyNotificationRules(ctx context.Context, userID influxdb.ID, rules []*stateRule) (applier, func(influxdb.ID) error) { +func (s *Service) applyNotificationRules(ctx context.Context, userID platform.ID, rules []*stateRule) (applier, func(platform.ID) error) { mutex := new(doMutex) rollbackEndpoints := make([]*stateRule, 0, len(rules)) - createFn := func(ctx context.Context, i int, orgID, userID influxdb.ID) *applyErrBody { + createFn := func(ctx context.Context, i int, orgID, userID platform.ID) *applyErrBody { var rule *stateRule mutex.Do(func() { rules[i].orgID = orgID @@ -2327,7 +2330,7 @@ func (s *Service) applyNotificationRules(ctx context.Context, userID influxdb.ID return nil } - rollbackFn := func(_ influxdb.ID) error { + rollbackFn := func(_ platform.ID) error { return s.rollbackNotificationRules(ctx, userID, rollbackEndpoints) } @@ -2337,16 +2340,16 @@ func (s *Service) applyNotificationRules(ctx context.Context, userID influxdb.ID fn: createFn, }, rollbacker: rollbacker{ - fn: func(_ influxdb.ID) error { return nil }, + fn: func(_ platform.ID) error { return nil }, }, }, rollbackFn } -func (s *Service) applyNotificationRule(ctx context.Context, r *stateRule, userID influxdb.ID) (influxdb.NotificationRule, error) { +func (s *Service) applyNotificationRule(ctx context.Context, r *stateRule, userID platform.ID) (influxdb.NotificationRule, error) { switch { case IsRemoval(r.stateStatus): if err := s.ruleSVC.DeleteNotificationRule(ctx, r.ID()); err != nil { - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors2.ErrorCode(err) == errors2.ENotFound { return nil, nil } return nil, applyFailErr("delete", r.stateIdentity(), err) @@ -2375,13 +2378,13 @@ func (s *Service) applyNotificationRule(ctx context.Context, r *stateRule, userI } } -func (s *Service) rollbackNotificationRules(ctx context.Context, userID influxdb.ID, rules []*stateRule) error { +func (s *Service) rollbackNotificationRules(ctx context.Context, userID platform.ID, rules []*stateRule) error { rollbackFn := func(r *stateRule) error { if !IsNew(r.stateStatus) && r.existing == nil { return nil } - existingRuleFn := func(endpointID influxdb.ID) influxdb.NotificationRule { + existingRuleFn := func(endpointID platform.ID) influxdb.NotificationRule { switch rr := r.existing.(type) { case *rule.HTTP: rr.EndpointID = endpointID @@ -2448,14 +2451,14 @@ func (s *Service) applySecrets(secrets map[string]string) applier { if len(secrets) == 0 { return applier{ - rollbacker: rollbacker{fn: func(orgID influxdb.ID) error { return nil }}, + rollbacker: rollbacker{fn: func(orgID platform.ID) error { return nil }}, } } mutex := new(doMutex) rollbackSecrets := make([]string, 0) - createFn := func(ctx context.Context, i int, orgID, userID influxdb.ID) *applyErrBody { + createFn := func(ctx context.Context, i int, orgID, userID platform.ID) *applyErrBody { err := s.secretSVC.PutSecrets(ctx, orgID, secrets) if err != nil { return &applyErrBody{name: "secrets", msg: err.Error()} @@ -2477,7 +2480,7 @@ func (s *Service) applySecrets(secrets map[string]string) applier { }, rollbacker: rollbacker{ resource: resource, - fn: func(orgID influxdb.ID) error { + fn: func(orgID platform.ID) error { return s.secretSVC.DeleteSecret(context.Background(), orgID) }, }, @@ -2490,7 +2493,7 @@ func (s *Service) applyTasks(ctx context.Context, tasks []*stateTask) applier { mutex := new(doMutex) rollbackTasks := make([]*stateTask, 0, len(tasks)) - createFn := func(ctx context.Context, i int, orgID, userID influxdb.ID) *applyErrBody { + createFn := func(ctx context.Context, i int, orgID, userID platform.ID) *applyErrBody { var t *stateTask mutex.Do(func() { tasks[i].orgID = orgID @@ -2520,21 +2523,21 @@ func (s *Service) applyTasks(ctx context.Context, tasks []*stateTask) applier { }, rollbacker: rollbacker{ resource: resource, - fn: func(_ influxdb.ID) error { + fn: func(_ platform.ID) error { return s.rollbackTasks(ctx, rollbackTasks) }, }, } } -func (s *Service) applyTask(ctx context.Context, userID influxdb.ID, t *stateTask) (influxdb.Task, error) { +func (s *Service) applyTask(ctx context.Context, userID platform.ID, t *stateTask) (influxdb.Task, error) { if isRestrictedTask(t.existing) { return *t.existing, nil } switch { case IsRemoval(t.stateStatus): if err := s.taskSVC.DeleteTask(ctx, t.ID()); err != nil { - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors2.ErrorCode(err) == errors2.ENotFound { return influxdb.Task{}, nil } return influxdb.Task{}, applyFailErr("delete", t.stateIdentity(), err) @@ -2650,13 +2653,13 @@ func (s *Service) rollbackTasks(ctx context.Context, tasks []*stateTask) error { return nil } -func (s *Service) applyTelegrafs(ctx context.Context, userID influxdb.ID, teles []*stateTelegraf) applier { +func (s *Service) applyTelegrafs(ctx context.Context, userID platform.ID, teles []*stateTelegraf) applier { const resource = "telegrafs" mutex := new(doMutex) rollbackTelegrafs := make([]*stateTelegraf, 0, len(teles)) - createFn := func(ctx context.Context, i int, orgID, userID influxdb.ID) *applyErrBody { + createFn := func(ctx context.Context, i int, orgID, userID platform.ID) *applyErrBody { var t *stateTelegraf mutex.Do(func() { teles[i].orgID = orgID @@ -2686,18 +2689,18 @@ func (s *Service) applyTelegrafs(ctx context.Context, userID influxdb.ID, teles }, rollbacker: rollbacker{ resource: resource, - fn: func(_ influxdb.ID) error { + fn: func(_ platform.ID) error { return s.rollbackTelegrafConfigs(ctx, userID, rollbackTelegrafs) }, }, } } -func (s *Service) applyTelegrafConfig(ctx context.Context, userID influxdb.ID, t *stateTelegraf) (influxdb.TelegrafConfig, error) { +func (s *Service) applyTelegrafConfig(ctx context.Context, userID platform.ID, t *stateTelegraf) (influxdb.TelegrafConfig, error) { switch { case IsRemoval(t.stateStatus): if err := s.teleSVC.DeleteTelegrafConfig(ctx, t.ID()); err != nil { - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors2.ErrorCode(err) == errors2.ENotFound { return influxdb.TelegrafConfig{}, nil } return influxdb.TelegrafConfig{}, applyFailErr("delete", t.stateIdentity(), err) @@ -2720,7 +2723,7 @@ func (s *Service) applyTelegrafConfig(ctx context.Context, userID influxdb.ID, t } } -func (s *Service) rollbackTelegrafConfigs(ctx context.Context, userID influxdb.ID, cfgs []*stateTelegraf) error { +func (s *Service) rollbackTelegrafConfigs(ctx context.Context, userID platform.ID, cfgs []*stateTelegraf) error { rollbackFn := func(t *stateTelegraf) error { if !IsNew(t.stateStatus) && t.existing == nil { return nil @@ -2759,7 +2762,7 @@ func (s *Service) applyVariables(ctx context.Context, vars []*stateVariable) app mutex := new(doMutex) rollBackVars := make([]*stateVariable, 0, len(vars)) - createFn := func(ctx context.Context, i int, orgID, userID influxdb.ID) *applyErrBody { + createFn := func(ctx context.Context, i int, orgID, userID platform.ID) *applyErrBody { var v *stateVariable mutex.Do(func() { vars[i].orgID = orgID @@ -2790,7 +2793,7 @@ func (s *Service) applyVariables(ctx context.Context, vars []*stateVariable) app }, rollbacker: rollbacker{ resource: resource, - fn: func(_ influxdb.ID) error { return s.rollbackVariables(ctx, rollBackVars) }, + fn: func(_ platform.ID) error { return s.rollbackVariables(ctx, rollBackVars) }, }, } } @@ -2838,7 +2841,7 @@ func (s *Service) rollbackVariables(ctx context.Context, variables []*stateVaria func (s *Service) applyVariable(ctx context.Context, v *stateVariable) (influxdb.Variable, error) { switch { case IsRemoval(v.stateStatus): - if err := s.varSVC.DeleteVariable(ctx, v.id); err != nil && influxdb.ErrorCode(err) != influxdb.ENotFound { + if err := s.varSVC.DeleteVariable(ctx, v.id); err != nil && errors2.ErrorCode(err) != errors2.ENotFound { return influxdb.Variable{}, applyFailErr("delete", v.stateIdentity(), err) } if v.existing == nil { @@ -2880,7 +2883,7 @@ func (s *Service) removeLabelMappings(ctx context.Context, labelMappings []state var rollbackMappings []stateLabelMappingForRemoval mutex := new(doMutex) - createFn := func(ctx context.Context, i int, orgID, userID influxdb.ID) *applyErrBody { + createFn := func(ctx context.Context, i int, orgID, userID platform.ID) *applyErrBody { var mapping stateLabelMappingForRemoval mutex.Do(func() { mapping = labelMappings[i] @@ -2891,7 +2894,7 @@ func (s *Service) removeLabelMappings(ctx context.Context, labelMappings []state ResourceID: mapping.ResourceID, ResourceType: mapping.ResourceType, }) - if err != nil && influxdb.ErrorCode(err) != influxdb.ENotFound { + if err != nil && errors2.ErrorCode(err) != errors2.ENotFound { return &applyErrBody{ name: fmt.Sprintf("%s:%s:%s", mapping.ResourceType, mapping.ResourceID, mapping.LabelID), msg: err.Error(), @@ -2911,7 +2914,7 @@ func (s *Service) removeLabelMappings(ctx context.Context, labelMappings []state }, rollbacker: rollbacker{ resource: resource, - fn: func(_ influxdb.ID) error { return s.rollbackRemoveLabelMappings(ctx, rollbackMappings) }, + fn: func(_ platform.ID) error { return s.rollbackRemoveLabelMappings(ctx, rollbackMappings) }, }, } } @@ -2949,7 +2952,7 @@ func (s *Service) applyLabelMappings(ctx context.Context, labelMappings []stateL mutex := new(doMutex) rollbackMappings := make([]stateLabelMapping, 0, len(labelMappings)) - createFn := func(ctx context.Context, i int, orgID, userID influxdb.ID) *applyErrBody { + createFn := func(ctx context.Context, i int, orgID, userID platform.ID) *applyErrBody { var mapping stateLabelMapping mutex.Do(func() { mapping = labelMappings[i] @@ -2993,7 +2996,7 @@ func (s *Service) applyLabelMappings(ctx context.Context, labelMappings []stateL }, rollbacker: rollbacker{ resource: resource, - fn: func(_ influxdb.ID) error { return s.rollbackLabelMappings(ctx, rollbackMappings) }, + fn: func(_ platform.ID) error { return s.rollbackLabelMappings(ctx, rollbackMappings) }, }, } } @@ -3027,7 +3030,7 @@ func (s *Service) templateFromApplyOpts(ctx context.Context, opt ApplyOpt) (*Tem return Combine(opt.Templates, ValidWithoutResources()) } -func (s *Service) getStackRemoteTemplates(ctx context.Context, stackID influxdb.ID) ([]*Template, error) { +func (s *Service) getStackRemoteTemplates(ctx context.Context, stackID platform.ID) ([]*Template, error) { stack, err := s.store.ReadStackByID(ctx, stackID) if err != nil { return nil, err @@ -3038,8 +3041,8 @@ func (s *Service) getStackRemoteTemplates(ctx context.Context, stackID influxdb. for _, rawURL := range lastEvent.TemplateURLs { u, err := url.Parse(rawURL) if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInternal, + return nil, &errors2.Error{ + Code: errors2.EInternal, Msg: "failed to parse url", Err: err, } @@ -3069,7 +3072,7 @@ func (s *Service) getStackRemoteTemplates(ctx context.Context, stackID influxdb. return remotes, nil } -func (s *Service) updateStackAfterSuccess(ctx context.Context, stackID influxdb.ID, state *stateCoordinator, sources []string) error { +func (s *Service) updateStackAfterSuccess(ctx context.Context, stackID platform.ID, state *stateCoordinator, sources []string) error { stack, err := s.store.ReadStackByID(ctx, stackID) if err != nil { return err @@ -3195,7 +3198,7 @@ func (s *Service) updateStackAfterSuccess(ctx context.Context, stackID influxdb. return s.store.UpdateStack(ctx, stack) } -func (s *Service) updateStackAfterRollback(ctx context.Context, stackID influxdb.ID, state *stateCoordinator, sources []string) error { +func (s *Service) updateStackAfterRollback(ctx context.Context, stackID platform.ID, state *stateCoordinator, sources []string) error { stack, err := s.store.ReadStackByID(ctx, stackID) if err != nil { return err @@ -3316,7 +3319,7 @@ func (s *Service) updateStackAfterRollback(ctx context.Context, stackID influxdb return s.store.UpdateStack(ctx, stack) } -func (s *Service) findLabel(ctx context.Context, orgID influxdb.ID, l *stateLabel) (*influxdb.Label, error) { +func (s *Service) findLabel(ctx context.Context, orgID platform.ID, l *stateLabel) (*influxdb.Label, error) { if l.ID() != 0 { return s.labelSVC.FindLabelByID(ctx, l.ID()) } @@ -3334,7 +3337,7 @@ func (s *Service) findLabel(ctx context.Context, orgID influxdb.ID, l *stateLabe return existingLabels[0], nil } -func (s *Service) getAllPlatformVariables(ctx context.Context, orgID influxdb.ID) ([]*influxdb.Variable, error) { +func (s *Service) getAllPlatformVariables(ctx context.Context, orgID platform.ID) ([]*influxdb.Variable, error) { const limit = 100 var ( @@ -3361,7 +3364,7 @@ func (s *Service) getAllPlatformVariables(ctx context.Context, orgID influxdb.ID return existingVars, nil } -func (s *Service) getAllChecks(ctx context.Context, orgID influxdb.ID) ([]influxdb.Check, error) { +func (s *Service) getAllChecks(ctx context.Context, orgID platform.ID) ([]influxdb.Check, error) { filter := influxdb.CheckFilter{OrgID: &orgID} const limit = 100 @@ -3386,7 +3389,7 @@ func (s *Service) getAllChecks(ctx context.Context, orgID influxdb.ID) ([]influx return out, nil } -func (s *Service) getNotificationRules(ctx context.Context, orgID influxdb.ID) ([]influxdb.NotificationRule, error) { +func (s *Service) getNotificationRules(ctx context.Context, orgID platform.ID) ([]influxdb.NotificationRule, error) { filter := influxdb.NotificationRuleFilter{OrgID: &orgID} const limit = 100 @@ -3409,10 +3412,10 @@ func (s *Service) getNotificationRules(ctx context.Context, orgID influxdb.ID) ( } -func (s *Service) getAllTasks(ctx context.Context, orgID influxdb.ID) ([]*influxdb.Task, error) { +func (s *Service) getAllTasks(ctx context.Context, orgID platform.ID) ([]*influxdb.Task, error) { var ( out []*influxdb.Task - afterID *influxdb.ID + afterID *platform.ID ) for { f := influxdb.TaskFilter{ @@ -3462,8 +3465,8 @@ func applyFailErr(method string, ident stateIdentity, err error) error { return ierrors.Wrap(err, msg) } -func getLabelIDMap(ctx context.Context, labelSVC influxdb.LabelService, labelNames []string) (map[influxdb.ID]bool, error) { - mLabelIDs := make(map[influxdb.ID]bool) +func getLabelIDMap(ctx context.Context, labelSVC influxdb.LabelService, labelNames []string) (map[platform.ID]bool, error) { + mLabelIDs := make(map[platform.ID]bool) for _, labelName := range labelNames { iLabels, err := labelSVC.FindLabels(ctx, influxdb.LabelFilter{ Name: labelName, @@ -3509,12 +3512,12 @@ type ( rollbacker struct { resource string - fn func(orgID influxdb.ID) error + fn func(orgID platform.ID) error } creater struct { entries int - fn func(ctx context.Context, i int, orgID, userID influxdb.ID) *applyErrBody + fn func(ctx context.Context, i int, orgID, userID platform.ID) *applyErrBody } ) @@ -3532,7 +3535,7 @@ func newRollbackCoordinator(logger *zap.Logger, reqLimit int) *rollbackCoordinat } } -func (r *rollbackCoordinator) runTilEnd(ctx context.Context, orgID, userID influxdb.ID, appliers ...applier) error { +func (r *rollbackCoordinator) runTilEnd(ctx context.Context, orgID, userID platform.ID, appliers ...applier) error { errStr := newErrStream(ctx) wg := new(sync.WaitGroup) @@ -3581,7 +3584,7 @@ func (r *rollbackCoordinator) runTilEnd(ctx context.Context, orgID, userID influ return errStr.close() } -func (r *rollbackCoordinator) rollback(l *zap.Logger, err *error, orgID influxdb.ID) { +func (r *rollbackCoordinator) rollback(l *zap.Logger, err *error, orgID platform.ID) { if *err == nil { return } @@ -3679,7 +3682,7 @@ func validURLs(urls []string) error { for _, u := range urls { if _, err := url.Parse(u); err != nil { msg := fmt.Sprintf("url invalid for entry %q", u) - return influxErr(influxdb.EInvalid, msg) + return influxErr(errors2.EInvalid, msg) } } return nil @@ -3705,18 +3708,18 @@ func failedValidationErr(err error) error { if err == nil { return nil } - return &influxdb.Error{Code: influxdb.EUnprocessableEntity, Err: err} + return &errors2.Error{Code: errors2.EUnprocessableEntity, Err: err} } func internalErr(err error) error { if err == nil { return nil } - return influxErr(influxdb.EInternal, err) + return influxErr(errors2.EInternal, err) } -func influxErr(code string, errArg interface{}, rest ...interface{}) *influxdb.Error { - err := &influxdb.Error{ +func influxErr(code string, errArg interface{}, rest ...interface{}) *errors2.Error { + err := &errors2.Error{ Code: code, } for _, a := range append(rest, errArg) { diff --git a/pkger/service_auth.go b/pkger/service_auth.go index a54828ad110..5dcacfd4b7e 100644 --- a/pkger/service_auth.go +++ b/pkger/service_auth.go @@ -3,12 +3,14 @@ package pkger import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) type AuthAgent interface { - IsWritable(ctx context.Context, orgID influxdb.ID, resType influxdb.ResourceType) error - OrgPermissions(ctx context.Context, orgID influxdb.ID, action influxdb.Action, rest ...influxdb.Action) error + IsWritable(ctx context.Context, orgID platform.ID, resType influxdb.ResourceType) error + OrgPermissions(ctx context.Context, orgID platform.ID, action influxdb.Action, rest ...influxdb.Action) error } type authMW struct { @@ -28,7 +30,7 @@ func MWAuth(authAgent AuthAgent) SVCMiddleware { } } -func (s *authMW) InitStack(ctx context.Context, userID influxdb.ID, newStack StackCreate) (Stack, error) { +func (s *authMW) InitStack(ctx context.Context, userID platform.ID, newStack StackCreate) (Stack, error) { err := s.authAgent.IsWritable(ctx, newStack.OrgID, ResourceTypeStack) if err != nil { return Stack{}, err @@ -36,7 +38,7 @@ func (s *authMW) InitStack(ctx context.Context, userID influxdb.ID, newStack Sta return s.next.InitStack(ctx, userID, newStack) } -func (s *authMW) UninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) (Stack, error) { +func (s *authMW) UninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) (Stack, error) { err := s.authAgent.IsWritable(ctx, identifiers.OrgID, ResourceTypeStack) if err != nil { return Stack{}, err @@ -44,7 +46,7 @@ func (s *authMW) UninstallStack(ctx context.Context, identifiers struct{ OrgID, return s.next.UninstallStack(ctx, identifiers) } -func (s *authMW) DeleteStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) error { +func (s *authMW) DeleteStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) error { err := s.authAgent.IsWritable(ctx, identifiers.OrgID, ResourceTypeStack) if err != nil { return err @@ -52,7 +54,7 @@ func (s *authMW) DeleteStack(ctx context.Context, identifiers struct{ OrgID, Use return s.next.DeleteStack(ctx, identifiers) } -func (s *authMW) ListStacks(ctx context.Context, orgID influxdb.ID, f ListFilter) ([]Stack, error) { +func (s *authMW) ListStacks(ctx context.Context, orgID platform.ID, f ListFilter) ([]Stack, error) { err := s.authAgent.OrgPermissions(ctx, orgID, influxdb.ReadAction) if err != nil { return nil, err @@ -60,7 +62,7 @@ func (s *authMW) ListStacks(ctx context.Context, orgID influxdb.ID, f ListFilter return s.next.ListStacks(ctx, orgID, f) } -func (s *authMW) ReadStack(ctx context.Context, id influxdb.ID) (Stack, error) { +func (s *authMW) ReadStack(ctx context.Context, id platform.ID) (Stack, error) { st, err := s.next.ReadStack(ctx, id) if err != nil { return Stack{}, err @@ -99,10 +101,10 @@ func (s *authMW) Export(ctx context.Context, opts ...ExportOptFn) (*Template, er return s.next.Export(ctx, opts...) } -func (s *authMW) DryRun(ctx context.Context, orgID, userID influxdb.ID, opts ...ApplyOptFn) (ImpactSummary, error) { +func (s *authMW) DryRun(ctx context.Context, orgID, userID platform.ID, opts ...ApplyOptFn) (ImpactSummary, error) { return s.next.DryRun(ctx, orgID, userID, opts...) } -func (s *authMW) Apply(ctx context.Context, orgID, userID influxdb.ID, opts ...ApplyOptFn) (ImpactSummary, error) { +func (s *authMW) Apply(ctx context.Context, orgID, userID platform.ID, opts ...ApplyOptFn) (ImpactSummary, error) { return s.next.Apply(ctx, orgID, userID, opts...) } diff --git a/pkger/service_logging.go b/pkger/service_logging.go index b34cd7838cc..9cf5fb765a9 100644 --- a/pkger/service_logging.go +++ b/pkger/service_logging.go @@ -4,7 +4,8 @@ import ( "context" "time" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "go.uber.org/zap" ) @@ -25,7 +26,7 @@ func MWLogging(log *zap.Logger) SVCMiddleware { var _ SVC = (*loggingMW)(nil) -func (s *loggingMW) InitStack(ctx context.Context, userID influxdb.ID, newStack StackCreate) (stack Stack, err error) { +func (s *loggingMW) InitStack(ctx context.Context, userID platform.ID, newStack StackCreate) (stack Stack, err error) { defer func(start time.Time) { if err == nil { return @@ -43,7 +44,7 @@ func (s *loggingMW) InitStack(ctx context.Context, userID influxdb.ID, newStack return s.next.InitStack(ctx, userID, newStack) } -func (s *loggingMW) UninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) (_ Stack, err error) { +func (s *loggingMW) UninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) (_ Stack, err error) { defer func(start time.Time) { if err == nil { return @@ -61,7 +62,7 @@ func (s *loggingMW) UninstallStack(ctx context.Context, identifiers struct{ OrgI return s.next.UninstallStack(ctx, identifiers) } -func (s *loggingMW) DeleteStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) (err error) { +func (s *loggingMW) DeleteStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) (err error) { defer func(start time.Time) { if err == nil { return @@ -79,7 +80,7 @@ func (s *loggingMW) DeleteStack(ctx context.Context, identifiers struct{ OrgID, return s.next.DeleteStack(ctx, identifiers) } -func (s *loggingMW) ListStacks(ctx context.Context, orgID influxdb.ID, f ListFilter) (stacks []Stack, err error) { +func (s *loggingMW) ListStacks(ctx context.Context, orgID platform.ID, f ListFilter) (stacks []Stack, err error) { defer func(start time.Time) { if err == nil { return @@ -102,7 +103,7 @@ func (s *loggingMW) ListStacks(ctx context.Context, orgID influxdb.ID, f ListFil return s.next.ListStacks(ctx, orgID, f) } -func (s *loggingMW) ReadStack(ctx context.Context, id influxdb.ID) (st Stack, err error) { +func (s *loggingMW) ReadStack(ctx context.Context, id platform.ID) (st Stack, err error) { defer func(start time.Time) { if err != nil { s.logger.Error("failed to read stack", @@ -153,7 +154,7 @@ func (s *loggingMW) Export(ctx context.Context, opts ...ExportOptFn) (template * return s.next.Export(ctx, opts...) } -func (s *loggingMW) DryRun(ctx context.Context, orgID, userID influxdb.ID, opts ...ApplyOptFn) (impact ImpactSummary, err error) { +func (s *loggingMW) DryRun(ctx context.Context, orgID, userID platform.ID, opts ...ApplyOptFn) (impact ImpactSummary, err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -181,7 +182,7 @@ func (s *loggingMW) DryRun(ctx context.Context, orgID, userID influxdb.ID, opts return s.next.DryRun(ctx, orgID, userID, opts...) } -func (s *loggingMW) Apply(ctx context.Context, orgID, userID influxdb.ID, opts ...ApplyOptFn) (impact ImpactSummary, err error) { +func (s *loggingMW) Apply(ctx context.Context, orgID, userID platform.ID, opts ...ApplyOptFn) (impact ImpactSummary, err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { diff --git a/pkger/service_metrics.go b/pkger/service_metrics.go index 03c72ffe71b..0b149168bdc 100644 --- a/pkger/service_metrics.go +++ b/pkger/service_metrics.go @@ -7,7 +7,8 @@ import ( "strconv" "strings" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/metric" "github.com/influxdata/influxdb/v2/kit/prom" "github.com/prometheus/client_golang/prometheus" @@ -42,30 +43,30 @@ func MWMetrics(reg *prom.Registry) SVCMiddleware { } } -func (s *mwMetrics) InitStack(ctx context.Context, userID influxdb.ID, newStack StackCreate) (Stack, error) { +func (s *mwMetrics) InitStack(ctx context.Context, userID platform.ID, newStack StackCreate) (Stack, error) { rec := s.rec.Record("init_stack") stack, err := s.next.InitStack(ctx, userID, newStack) return stack, rec(err) } -func (s *mwMetrics) UninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) (Stack, error) { +func (s *mwMetrics) UninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) (Stack, error) { rec := s.rec.Record("uninstall_stack") stack, err := s.next.UninstallStack(ctx, identifiers) return stack, rec(err) } -func (s *mwMetrics) DeleteStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) error { +func (s *mwMetrics) DeleteStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) error { rec := s.rec.Record("delete_stack") return rec(s.next.DeleteStack(ctx, identifiers)) } -func (s *mwMetrics) ListStacks(ctx context.Context, orgID influxdb.ID, f ListFilter) ([]Stack, error) { +func (s *mwMetrics) ListStacks(ctx context.Context, orgID platform.ID, f ListFilter) ([]Stack, error) { rec := s.rec.Record("list_stacks") stacks, err := s.next.ListStacks(ctx, orgID, f) return stacks, rec(err) } -func (s *mwMetrics) ReadStack(ctx context.Context, id influxdb.ID) (Stack, error) { +func (s *mwMetrics) ReadStack(ctx context.Context, id platform.ID) (Stack, error) { rec := s.rec.Record("read_stack") stack, err := s.next.ReadStack(ctx, id) return stack, rec(err) @@ -96,13 +97,13 @@ func (s *mwMetrics) Export(ctx context.Context, opts ...ExportOptFn) (*Template, })) } -func (s *mwMetrics) DryRun(ctx context.Context, orgID, userID influxdb.ID, opts ...ApplyOptFn) (ImpactSummary, error) { +func (s *mwMetrics) DryRun(ctx context.Context, orgID, userID platform.ID, opts ...ApplyOptFn) (ImpactSummary, error) { rec := s.rec.Record("dry_run") impact, err := s.next.DryRun(ctx, orgID, userID, opts...) return impact, rec(err, applyMetricAdditions(orgID, userID, impact.Sources)) } -func (s *mwMetrics) Apply(ctx context.Context, orgID, userID influxdb.ID, opts ...ApplyOptFn) (ImpactSummary, error) { +func (s *mwMetrics) Apply(ctx context.Context, orgID, userID platform.ID, opts ...ApplyOptFn) (ImpactSummary, error) { rec := s.rec.Record("apply") impact, err := s.next.Apply(ctx, orgID, userID, opts...) if err == nil { @@ -111,7 +112,7 @@ func (s *mwMetrics) Apply(ctx context.Context, orgID, userID influxdb.ID, opts . return impact, rec(err, applyMetricAdditions(orgID, userID, impact.Sources)) } -func applyMetricAdditions(orgID, userID influxdb.ID, sources []string) func(*metric.CollectFnOpts) { +func applyMetricAdditions(orgID, userID platform.ID, sources []string) func(*metric.CollectFnOpts) { return metric.RecordAdditional(map[string]interface{}{ "org_id": orgID.String(), "sources": sources, diff --git a/pkger/service_models.go b/pkger/service_models.go index 1cee6b0527f..a348b9ab68e 100644 --- a/pkger/service_models.go +++ b/pkger/service_models.go @@ -4,6 +4,8 @@ import ( "reflect" "sort" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/notification/rule" ) @@ -445,7 +447,7 @@ func (s *stateCoordinator) reconcileStackResources(stackResources []StackResourc } func (s *stateCoordinator) reconcileLabelMappings(stackResources []StackResource) { - mLabelMetaNameToID := make(map[string]influxdb.ID) + mLabelMetaNameToID := make(map[string]platform.ID) for _, r := range stackResources { if r.Kind.is(KindLabel) { mLabelMetaNameToID[r.MetaName] = r.ID @@ -558,7 +560,7 @@ func (s *stateCoordinator) Contains(k Kind, metaName string) bool { } // setObjectID sets the id for the resource graphed from the object the key identifies. -func (s *stateCoordinator) setObjectID(k Kind, metaName string, id influxdb.ID) { +func (s *stateCoordinator) setObjectID(k Kind, metaName string, id platform.ID) { idSetFn, ok := s.getObjectIDSetter(k, metaName) if !ok { return @@ -570,7 +572,7 @@ func (s *stateCoordinator) setObjectID(k Kind, metaName string, id influxdb.ID) // The metaName and kind are used as the unique identifier, when calling this it will // overwrite any existing value if one exists. If desired, check for the value by using // the Contains method. -func (s *stateCoordinator) addObjectForRemoval(k Kind, metaName string, id influxdb.ID) { +func (s *stateCoordinator) addObjectForRemoval(k Kind, metaName string, id platform.ID) { newIdentity := identity{ name: &references{val: metaName}, } @@ -636,29 +638,29 @@ func (s *stateCoordinator) addObjectForRemoval(k Kind, metaName string, id influ } } -func (s *stateCoordinator) getObjectIDSetter(k Kind, metaName string) (func(influxdb.ID), bool) { +func (s *stateCoordinator) getObjectIDSetter(k Kind, metaName string) (func(platform.ID), bool) { switch k { case KindBucket: r, ok := s.mBuckets[metaName] - return func(id influxdb.ID) { + return func(id platform.ID) { r.id = id r.stateStatus = StateStatusExists }, ok case KindCheck, KindCheckDeadman, KindCheckThreshold: r, ok := s.mChecks[metaName] - return func(id influxdb.ID) { + return func(id platform.ID) { r.id = id r.stateStatus = StateStatusExists }, ok case KindDashboard: r, ok := s.mDashboards[metaName] - return func(id influxdb.ID) { + return func(id platform.ID) { r.id = id r.stateStatus = StateStatusExists }, ok case KindLabel: r, ok := s.mLabels[metaName] - return func(id influxdb.ID) { + return func(id platform.ID) { r.id = id r.stateStatus = StateStatusExists }, ok @@ -667,31 +669,31 @@ func (s *stateCoordinator) getObjectIDSetter(k Kind, metaName string) (func(infl KindNotificationEndpointPagerDuty, KindNotificationEndpointSlack: r, ok := s.mEndpoints[metaName] - return func(id influxdb.ID) { + return func(id platform.ID) { r.id = id r.stateStatus = StateStatusExists }, ok case KindNotificationRule: r, ok := s.mRules[metaName] - return func(id influxdb.ID) { + return func(id platform.ID) { r.id = id r.stateStatus = StateStatusExists }, ok case KindTask: r, ok := s.mTasks[metaName] - return func(id influxdb.ID) { + return func(id platform.ID) { r.id = id r.stateStatus = StateStatusExists }, ok case KindTelegraf: r, ok := s.mTelegrafs[metaName] - return func(id influxdb.ID) { + return func(id platform.ID) { r.id = id r.stateStatus = StateStatusExists }, ok case KindVariable: r, ok := s.mVariables[metaName] - return func(id influxdb.ID) { + return func(id platform.ID) { r.id = id r.stateStatus = StateStatusExists }, ok @@ -701,7 +703,7 @@ func (s *stateCoordinator) getObjectIDSetter(k Kind, metaName string) (func(infl } type stateIdentity struct { - id influxdb.ID + id platform.ID name string metaName string resourceType influxdb.ResourceType @@ -713,7 +715,7 @@ func (s stateIdentity) exists() bool { } type stateBucket struct { - id, orgID influxdb.ID + id, orgID platform.ID stateStatus StateStatus labelAssociations []*stateLabel @@ -763,7 +765,7 @@ func (b *stateBucket) summarize() SummaryBucket { return sum } -func (b *stateBucket) ID() influxdb.ID { +func (b *stateBucket) ID() platform.ID { if !IsNew(b.stateStatus) && b.existing != nil { return b.existing.ID } @@ -797,7 +799,7 @@ func (b *stateBucket) shouldApply() bool { } type stateCheck struct { - id, orgID influxdb.ID + id, orgID platform.ID stateStatus StateStatus labelAssociations []*stateLabel @@ -805,7 +807,7 @@ type stateCheck struct { existing influxdb.Check } -func (c *stateCheck) ID() influxdb.ID { +func (c *stateCheck) ID() platform.ID { if !IsNew(c.stateStatus) && c.existing != nil { return c.existing.GetID() } @@ -863,7 +865,7 @@ func (c *stateCheck) summarize() SummaryCheck { } type stateDashboard struct { - id, orgID influxdb.ID + id, orgID platform.ID stateStatus StateStatus labelAssociations []*stateLabel @@ -871,7 +873,7 @@ type stateDashboard struct { existing *influxdb.Dashboard } -func (d *stateDashboard) ID() influxdb.ID { +func (d *stateDashboard) ID() platform.ID { if !IsNew(d.stateStatus) && d.existing != nil { return d.existing.ID } @@ -958,7 +960,7 @@ func (d *stateDashboard) summarize() SummaryDashboard { } type stateLabel struct { - id, orgID influxdb.ID + id, orgID platform.ID stateStatus StateStatus parserLabel *label @@ -996,7 +998,7 @@ func (l *stateLabel) summarize() SummaryLabel { return sum } -func (l *stateLabel) ID() influxdb.ID { +func (l *stateLabel) ID() platform.ID { if !IsNew(l.stateStatus) && l.existing != nil { return l.existing.ID } @@ -1083,9 +1085,9 @@ func stateLabelMappingToInfluxLabelMapping(mapping stateLabelMapping) influxdb.L } type stateLabelMappingForRemoval struct { - LabelID influxdb.ID + LabelID platform.ID LabelMetaName string - ResourceID influxdb.ID + ResourceID platform.ID ResourceMetaName string ResourceType influxdb.ResourceType } @@ -1102,7 +1104,7 @@ func (m *stateLabelMappingForRemoval) diffLabelMapping() DiffLabelMapping { } type stateEndpoint struct { - id, orgID influxdb.ID + id, orgID platform.ID stateStatus StateStatus labelAssociations []*stateLabel @@ -1110,7 +1112,7 @@ type stateEndpoint struct { existing influxdb.NotificationEndpoint } -func (e *stateEndpoint) ID() influxdb.ID { +func (e *stateEndpoint) ID() platform.ID { if !IsNew(e.stateStatus) && e.existing != nil { return e.existing.GetID() } @@ -1172,7 +1174,7 @@ func (e *stateEndpoint) summarize() SummaryNotificationEndpoint { } type stateRule struct { - id, orgID influxdb.ID + id, orgID platform.ID stateStatus StateStatus labelAssociations []*stateLabel @@ -1182,7 +1184,7 @@ type stateRule struct { existing influxdb.NotificationRule } -func (r *stateRule) ID() influxdb.ID { +func (r *stateRule) ID() platform.ID { if !IsNew(r.stateStatus) && r.existing != nil { return r.existing.GetID() } @@ -1270,7 +1272,7 @@ func (r *stateRule) diffRule() DiffNotificationRule { return sum } -func (r *stateRule) endpointID() influxdb.ID { +func (r *stateRule) endpointID() platform.ID { if r.associatedEndpoint != nil { return r.associatedEndpoint.ID() } @@ -1340,7 +1342,7 @@ func (r *stateRule) toInfluxRule() influxdb.NotificationRule { } type stateTask struct { - id, orgID influxdb.ID + id, orgID platform.ID stateStatus StateStatus labelAssociations []*stateLabel @@ -1348,7 +1350,7 @@ type stateTask struct { existing *influxdb.Task } -func (t *stateTask) ID() influxdb.ID { +func (t *stateTask) ID() platform.ID { if !IsNew(t.stateStatus) && t.existing != nil { return t.existing.ID } @@ -1417,7 +1419,7 @@ func (t *stateTask) summarize() SummaryTask { } type stateTelegraf struct { - id, orgID influxdb.ID + id, orgID platform.ID stateStatus StateStatus labelAssociations []*stateLabel @@ -1425,7 +1427,7 @@ type stateTelegraf struct { existing *influxdb.TelegrafConfig } -func (t *stateTelegraf) ID() influxdb.ID { +func (t *stateTelegraf) ID() platform.ID { if !IsNew(t.stateStatus) && t.existing != nil { return t.existing.ID } @@ -1472,7 +1474,7 @@ func (t *stateTelegraf) summarize() SummaryTelegraf { } type stateVariable struct { - id, orgID influxdb.ID + id, orgID platform.ID stateStatus StateStatus labelAssociations []*stateLabel @@ -1480,7 +1482,7 @@ type stateVariable struct { existing *influxdb.Variable } -func (v *stateVariable) ID() influxdb.ID { +func (v *stateVariable) ID() platform.ID { if !IsNew(v.stateStatus) && v.existing != nil { return v.existing.ID } diff --git a/pkger/service_test.go b/pkger/service_test.go index 63c806e6bf2..32806ba2323 100644 --- a/pkger/service_test.go +++ b/pkger/service_test.go @@ -13,6 +13,9 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" "github.com/influxdata/influxdb/v2/notification" @@ -38,10 +41,10 @@ func TestService(t *testing.T) { createFn: func(ctx context.Context, stack Stack) error { return nil }, - deleteFn: func(ctx context.Context, id influxdb.ID) error { + deleteFn: func(ctx context.Context, id platform.ID) error { return nil }, - readFn: func(ctx context.Context, id influxdb.ID) (Stack, error) { + readFn: func(ctx context.Context, id platform.ID) (Stack, error) { return Stack{ID: id}, nil }, updateFn: func(ctx context.Context, stack Stack) error { @@ -134,7 +137,7 @@ func TestService(t *testing.T) { impact, err := svc.DryRun( context.TODO(), - influxdb.ID(100), + platform.ID(100), 0, append(tt.applyOpts, ApplyWithTemplate(template))..., ) @@ -151,12 +154,12 @@ func TestService(t *testing.T) { t.Run("single bucket updated", func(t *testing.T) { testfileRunner(t, "testdata/bucket.yml", func(t *testing.T, template *Template) { fakeBktSVC := mock.NewBucketService() - fakeBktSVC.FindBucketByNameFn = func(_ context.Context, orgID influxdb.ID, name string) (*influxdb.Bucket, error) { + fakeBktSVC.FindBucketByNameFn = func(_ context.Context, orgID platform.ID, name string) (*influxdb.Bucket, error) { if name != "rucket-11" { return nil, errors.New("not found") } return &influxdb.Bucket{ - ID: influxdb.ID(1), + ID: platform.ID(1), OrgID: orgID, Name: name, Description: "old desc", @@ -165,7 +168,7 @@ func TestService(t *testing.T) { } svc := newTestService(WithBucketSVC(fakeBktSVC)) - impact, err := svc.DryRun(context.TODO(), influxdb.ID(100), 0, ApplyWithTemplate(template)) + impact, err := svc.DryRun(context.TODO(), platform.ID(100), 0, ApplyWithTemplate(template)) require.NoError(t, err) require.Len(t, impact.Diff.Buckets, 2) @@ -196,12 +199,12 @@ func TestService(t *testing.T) { t.Run("single bucket new", func(t *testing.T) { testfileRunner(t, "testdata/bucket.json", func(t *testing.T, template *Template) { fakeBktSVC := mock.NewBucketService() - fakeBktSVC.FindBucketByNameFn = func(_ context.Context, orgID influxdb.ID, name string) (*influxdb.Bucket, error) { + fakeBktSVC.FindBucketByNameFn = func(_ context.Context, orgID platform.ID, name string) (*influxdb.Bucket, error) { return nil, errors.New("not found") } svc := newTestService(WithBucketSVC(fakeBktSVC)) - impact, err := svc.DryRun(context.TODO(), influxdb.ID(100), 0, ApplyWithTemplate(template)) + impact, err := svc.DryRun(context.TODO(), platform.ID(100), 0, ApplyWithTemplate(template)) require.NoError(t, err) require.Len(t, impact.Diff.Buckets, 2) @@ -247,7 +250,7 @@ func TestService(t *testing.T) { t.Run("mixed update and creates", func(t *testing.T) { testfileRunner(t, "testdata/checks.yml", func(t *testing.T, template *Template) { fakeCheckSVC := mock.NewCheckService() - id := influxdb.ID(1) + id := platform.ID(1) existing := &icheck.Deadman{ Base: icheck.Base{ ID: id, @@ -264,7 +267,7 @@ func TestService(t *testing.T) { svc := newTestService(WithCheckSVC(fakeCheckSVC)) - impact, err := svc.DryRun(context.TODO(), influxdb.ID(100), 0, ApplyWithTemplate(template)) + impact, err := svc.DryRun(context.TODO(), platform.ID(100), 0, ApplyWithTemplate(template)) require.NoError(t, err) checks := impact.Diff.Checks @@ -334,7 +337,7 @@ func TestService(t *testing.T) { fakeLabelSVC.FindLabelsFn = func(_ context.Context, filter influxdb.LabelFilter) ([]*influxdb.Label, error) { return []*influxdb.Label{ { - ID: influxdb.ID(1), + ID: platform.ID(1), Name: filter.Name, Properties: map[string]string{ "color": "old color", @@ -345,7 +348,7 @@ func TestService(t *testing.T) { } svc := newTestService(WithLabelSVC(fakeLabelSVC)) - impact, err := svc.DryRun(context.TODO(), influxdb.ID(100), 0, ApplyWithTemplate(template)) + impact, err := svc.DryRun(context.TODO(), platform.ID(100), 0, ApplyWithTemplate(template)) require.NoError(t, err) require.Len(t, impact.Diff.Labels, 3) @@ -387,7 +390,7 @@ func TestService(t *testing.T) { } svc := newTestService(WithLabelSVC(fakeLabelSVC)) - impact, err := svc.DryRun(context.TODO(), influxdb.ID(100), 0, ApplyWithTemplate(template)) + impact, err := svc.DryRun(context.TODO(), platform.ID(100), 0, ApplyWithTemplate(template)) require.NoError(t, err) labels := impact.Diff.Labels @@ -444,7 +447,7 @@ func TestService(t *testing.T) { t.Run("mixed update and created", func(t *testing.T) { testfileRunner(t, "testdata/notification_endpoint.yml", func(t *testing.T, template *Template) { fakeEndpointSVC := mock.NewNotificationEndpointService() - id := influxdb.ID(1) + id := platform.ID(1) existing := &endpoint.HTTP{ Base: endpoint.Base{ ID: &id, @@ -462,7 +465,7 @@ func TestService(t *testing.T) { svc := newTestService(WithNotificationEndpointSVC(fakeEndpointSVC)) - impact, err := svc.DryRun(context.TODO(), influxdb.ID(100), 0, ApplyWithTemplate(template)) + impact, err := svc.DryRun(context.TODO(), platform.ID(100), 0, ApplyWithTemplate(template)) require.NoError(t, err) require.Len(t, impact.Diff.NotificationEndpoints, 5) @@ -551,7 +554,7 @@ func TestService(t *testing.T) { t.Run("mixed update and created", func(t *testing.T) { testfileRunner(t, "testdata/notification_rule.yml", func(t *testing.T, template *Template) { fakeEndpointSVC := mock.NewNotificationEndpointService() - id := influxdb.ID(1) + id := platform.ID(1) existing := &endpoint.HTTP{ Base: endpoint.Base{ ID: &id, @@ -570,7 +573,7 @@ func TestService(t *testing.T) { svc := newTestService(WithNotificationEndpointSVC(fakeEndpointSVC)) - impact, err := svc.DryRun(context.TODO(), influxdb.ID(100), 0, ApplyWithTemplate(template)) + impact, err := svc.DryRun(context.TODO(), platform.ID(100), 0, ApplyWithTemplate(template)) require.NoError(t, err) require.Len(t, impact.Diff.NotificationRules, 1) @@ -618,12 +621,12 @@ func TestService(t *testing.T) { t.Run("secrets not returns missing secrets", func(t *testing.T) { testfileRunner(t, "testdata/notification_endpoint_secrets.yml", func(t *testing.T, template *Template) { fakeSecretSVC := mock.NewSecretService() - fakeSecretSVC.GetSecretKeysFn = func(ctx context.Context, orgID influxdb.ID) ([]string, error) { + fakeSecretSVC.GetSecretKeysFn = func(ctx context.Context, orgID platform.ID) ([]string, error) { return []string{"rando-1", "rando-2"}, nil } svc := newTestService(WithSecretSVC(fakeSecretSVC)) - impact, err := svc.DryRun(context.TODO(), influxdb.ID(100), 0, ApplyWithTemplate(template)) + impact, err := svc.DryRun(context.TODO(), platform.ID(100), 0, ApplyWithTemplate(template)) require.NoError(t, err) assert.Equal(t, []string{"routing-key"}, impact.Summary.MissingSecrets) @@ -681,7 +684,7 @@ func TestService(t *testing.T) { fakeVarSVC.FindVariablesF = func(_ context.Context, filter influxdb.VariableFilter, opts ...influxdb.FindOptions) ([]*influxdb.Variable, error) { return []*influxdb.Variable{ { - ID: influxdb.ID(1), + ID: platform.ID(1), Name: "var-const-3", Description: "old desc", }, @@ -689,7 +692,7 @@ func TestService(t *testing.T) { } svc := newTestService(WithVariableSVC(fakeVarSVC)) - impact, err := svc.DryRun(context.TODO(), influxdb.ID(100), 0, ApplyWithTemplate(template)) + impact, err := svc.DryRun(context.TODO(), platform.ID(100), 0, ApplyWithTemplate(template)) require.NoError(t, err) variables := impact.Diff.Variables @@ -773,20 +776,20 @@ func TestService(t *testing.T) { testfileRunner(t, "testdata/bucket.yml", func(t *testing.T, template *Template) { fakeBktSVC := mock.NewBucketService() fakeBktSVC.CreateBucketFn = func(_ context.Context, b *influxdb.Bucket) error { - b.ID = influxdb.ID(b.RetentionPeriod) + b.ID = platform.ID(b.RetentionPeriod) return nil } - fakeBktSVC.FindBucketByNameFn = func(_ context.Context, id influxdb.ID, s string) (*influxdb.Bucket, error) { + fakeBktSVC.FindBucketByNameFn = func(_ context.Context, id platform.ID, s string) (*influxdb.Bucket, error) { // forces the bucket to be created a new return nil, errors.New("an error") } - fakeBktSVC.UpdateBucketFn = func(_ context.Context, id influxdb.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { + fakeBktSVC.UpdateBucketFn = func(_ context.Context, id platform.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { return &influxdb.Bucket{ID: id}, nil } svc := newTestService(WithBucketSVC(fakeBktSVC)) - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) impact, err := svc.Apply(context.TODO(), orgID, 0, ApplyWithTemplate(template)) require.NoError(t, err) @@ -813,15 +816,15 @@ func TestService(t *testing.T) { t.Run("will not apply bucket if no changes to be applied", func(t *testing.T) { testfileRunner(t, "testdata/bucket.yml", func(t *testing.T, template *Template) { - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) fakeBktSVC := mock.NewBucketService() - fakeBktSVC.FindBucketByNameFn = func(ctx context.Context, oid influxdb.ID, name string) (*influxdb.Bucket, error) { + fakeBktSVC.FindBucketByNameFn = func(ctx context.Context, oid platform.ID, name string) (*influxdb.Bucket, error) { if orgID != oid { return nil, errors.New("invalid org id") } - id := influxdb.ID(3) + id := platform.ID(3) if name == "display name" { id = 4 name = "rucket-22" @@ -837,7 +840,7 @@ func TestService(t *testing.T) { } return nil, errors.New("not found") } - fakeBktSVC.UpdateBucketFn = func(_ context.Context, id influxdb.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { + fakeBktSVC.UpdateBucketFn = func(_ context.Context, id platform.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { return &influxdb.Bucket{ID: id}, nil } @@ -871,7 +874,7 @@ func TestService(t *testing.T) { t.Run("rolls back all created buckets on an error", func(t *testing.T) { testfileRunner(t, "testdata/bucket.yml", func(t *testing.T, template *Template) { fakeBktSVC := mock.NewBucketService() - fakeBktSVC.FindBucketByNameFn = func(_ context.Context, id influxdb.ID, s string) (*influxdb.Bucket, error) { + fakeBktSVC.FindBucketByNameFn = func(_ context.Context, id platform.ID, s string) (*influxdb.Bucket, error) { // forces the bucket to be created a new return nil, errors.New("an error") } @@ -884,7 +887,7 @@ func TestService(t *testing.T) { svc := newTestService(WithBucketSVC(fakeBktSVC)) - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) _, err := svc.Apply(context.TODO(), orgID, 0, ApplyWithTemplate(template)) require.Error(t, err) @@ -898,14 +901,14 @@ func TestService(t *testing.T) { t.Run("successfully creates template of checks", func(t *testing.T) { testfileRunner(t, "testdata/checks.yml", func(t *testing.T, template *Template) { fakeCheckSVC := mock.NewCheckService() - fakeCheckSVC.CreateCheckFn = func(ctx context.Context, c influxdb.CheckCreate, id influxdb.ID) error { - c.SetID(influxdb.ID(fakeCheckSVC.CreateCheckCalls.Count() + 1)) + fakeCheckSVC.CreateCheckFn = func(ctx context.Context, c influxdb.CheckCreate, id platform.ID) error { + c.SetID(platform.ID(fakeCheckSVC.CreateCheckCalls.Count() + 1)) return nil } svc := newTestService(WithCheckSVC(fakeCheckSVC)) - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) impact, err := svc.Apply(context.TODO(), orgID, 0, ApplyWithTemplate(template)) require.NoError(t, err) @@ -937,8 +940,8 @@ func TestService(t *testing.T) { t.Run("rolls back all created checks on an error", func(t *testing.T) { testfileRunner(t, "testdata/checks.yml", func(t *testing.T, template *Template) { fakeCheckSVC := mock.NewCheckService() - fakeCheckSVC.CreateCheckFn = func(ctx context.Context, c influxdb.CheckCreate, id influxdb.ID) error { - c.SetID(influxdb.ID(fakeCheckSVC.CreateCheckCalls.Count() + 1)) + fakeCheckSVC.CreateCheckFn = func(ctx context.Context, c influxdb.CheckCreate, id platform.ID) error { + c.SetID(platform.ID(fakeCheckSVC.CreateCheckCalls.Count() + 1)) if fakeCheckSVC.CreateCheckCalls.Count() == 1 { return errors.New("hit that kill count") } @@ -947,7 +950,7 @@ func TestService(t *testing.T) { svc := newTestService(WithCheckSVC(fakeCheckSVC)) - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) _, err := svc.Apply(context.TODO(), orgID, 0, ApplyWithTemplate(template)) require.Error(t, err) @@ -966,13 +969,13 @@ func TestService(t *testing.T) { if err != nil { return nil } - l.ID = influxdb.ID(i) + l.ID = platform.ID(i) return nil } svc := newTestService(WithLabelSVC(fakeLabelSVC)) - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) impact, err := svc.Apply(context.TODO(), orgID, 0, ApplyWithTemplate(template)) require.NoError(t, err) @@ -1005,7 +1008,7 @@ func TestService(t *testing.T) { svc := newTestService(WithLabelSVC(fakeLabelSVC)) - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) _, err := svc.Apply(context.TODO(), orgID, 0, ApplyWithTemplate(template)) require.Error(t, err) @@ -1016,9 +1019,9 @@ func TestService(t *testing.T) { t.Run("will not apply label if no changes to be applied", func(t *testing.T) { testfileRunner(t, "testdata/label.yml", func(t *testing.T, template *Template) { - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) - stubExisting := func(name string, id influxdb.ID) *influxdb.Label { + stubExisting := func(name string, id platform.ID) *influxdb.Label { templateLabel := template.mLabels[name] return &influxdb.Label{ // makes all template changes same as they are on the existing @@ -1039,7 +1042,7 @@ func TestService(t *testing.T) { if f.Name != "label-1" && f.Name != "display name" { return nil, nil } - id := influxdb.ID(1) + id := platform.ID(1) name := f.Name if f.Name == "display name" { id = 3 @@ -1053,8 +1056,8 @@ func TestService(t *testing.T) { } return nil } - fakeLabelSVC.UpdateLabelFn = func(_ context.Context, id influxdb.ID, l influxdb.LabelUpdate) (*influxdb.Label, error) { - if id == influxdb.ID(3) { + fakeLabelSVC.UpdateLabelFn = func(_ context.Context, id platform.ID, l influxdb.LabelUpdate) (*influxdb.Label, error) { + if id == platform.ID(3) { return nil, errors.New("invalid id provided") } return &influxdb.Label{ID: id}, nil @@ -1088,16 +1091,16 @@ func TestService(t *testing.T) { testfileRunner(t, "testdata/dashboard.yml", func(t *testing.T, template *Template) { fakeDashSVC := mock.NewDashboardService() fakeDashSVC.CreateDashboardF = func(_ context.Context, d *influxdb.Dashboard) error { - d.ID = influxdb.ID(1) + d.ID = platform.ID(1) return nil } - fakeDashSVC.UpdateDashboardCellViewF = func(ctx context.Context, dID influxdb.ID, cID influxdb.ID, upd influxdb.ViewUpdate) (*influxdb.View, error) { + fakeDashSVC.UpdateDashboardCellViewF = func(ctx context.Context, dID platform.ID, cID platform.ID, upd influxdb.ViewUpdate) (*influxdb.View, error) { return &influxdb.View{}, nil } svc := newTestService(WithDashboardSVC(fakeDashSVC)) - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) impact, err := svc.Apply(context.TODO(), orgID, 0, ApplyWithTemplate(template)) require.NoError(t, err) @@ -1128,18 +1131,18 @@ func TestService(t *testing.T) { if fakeDashSVC.CreateDashboardCalls.Count() == 1 { return errors.New("blowed up ") } - d.ID = influxdb.ID(1) + d.ID = platform.ID(1) return nil } - deletedDashs := make(map[influxdb.ID]bool) - fakeDashSVC.DeleteDashboardF = func(_ context.Context, id influxdb.ID) error { + deletedDashs := make(map[platform.ID]bool) + fakeDashSVC.DeleteDashboardF = func(_ context.Context, id platform.ID) error { deletedDashs[id] = true return nil } svc := newTestService(WithDashboardSVC(fakeDashSVC)) - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) _, err := svc.Apply(context.TODO(), orgID, 0, ApplyWithTemplate(template)) require.Error(t, err) @@ -1157,7 +1160,7 @@ func TestService(t *testing.T) { fakeLabelSVC := mock.NewLabelService() fakeLabelSVC.CreateLabelFn = func(_ context.Context, l *influxdb.Label) error { - l.ID = influxdb.ID(rand.Int()) + l.ID = platform.ID(rand.Int()) return nil } fakeLabelSVC.CreateLabelMappingFn = func(_ context.Context, mapping *influxdb.LabelMapping) error { @@ -1174,7 +1177,7 @@ func TestService(t *testing.T) { WithLogger(zaptest.NewLogger(t)), )...) - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) _, err := svc.Apply(context.TODO(), orgID, 0, ApplyWithTemplate(template)) require.NoError(t, err) @@ -1190,7 +1193,7 @@ func TestService(t *testing.T) { fakeLabelSVC := mock.NewLabelService() fakeLabelSVC.CreateLabelFn = func(_ context.Context, l *influxdb.Label) error { - l.ID = influxdb.ID(fakeLabelSVC.CreateLabelCalls.Count() + 1) + l.ID = platform.ID(fakeLabelSVC.CreateLabelCalls.Count() + 1) return nil } fakeLabelSVC.CreateLabelMappingFn = func(_ context.Context, mapping *influxdb.LabelMapping) error { @@ -1210,7 +1213,7 @@ func TestService(t *testing.T) { WithLogger(zaptest.NewLogger(t)), )...) - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) _, err := svc.Apply(context.TODO(), orgID, 0, ApplyWithTemplate(template)) require.Error(t, err) @@ -1223,10 +1226,10 @@ func TestService(t *testing.T) { bktOpt := func() []ServiceSetterFn { fakeBktSVC := mock.NewBucketService() fakeBktSVC.CreateBucketFn = func(_ context.Context, b *influxdb.Bucket) error { - b.ID = influxdb.ID(rand.Int()) + b.ID = platform.ID(rand.Int()) return nil } - fakeBktSVC.FindBucketByNameFn = func(_ context.Context, id influxdb.ID, s string) (*influxdb.Bucket, error) { + fakeBktSVC.FindBucketByNameFn = func(_ context.Context, id platform.ID, s string) (*influxdb.Bucket, error) { // forces the bucket to be created a new return nil, errors.New("an error") } @@ -1245,8 +1248,8 @@ func TestService(t *testing.T) { t.Run("maps checks with labels", func(t *testing.T) { opts := func() []ServiceSetterFn { fakeCheckSVC := mock.NewCheckService() - fakeCheckSVC.CreateCheckFn = func(ctx context.Context, c influxdb.CheckCreate, id influxdb.ID) error { - c.Check.SetID(influxdb.ID(rand.Int())) + fakeCheckSVC.CreateCheckFn = func(ctx context.Context, c influxdb.CheckCreate, id platform.ID) error { + c.Check.SetID(platform.ID(rand.Int())) return nil } fakeCheckSVC.FindCheckFn = func(ctx context.Context, f influxdb.CheckFilter) (influxdb.Check, error) { @@ -1269,7 +1272,7 @@ func TestService(t *testing.T) { opts := func() []ServiceSetterFn { fakeDashSVC := mock.NewDashboardService() fakeDashSVC.CreateDashboardF = func(_ context.Context, d *influxdb.Dashboard) error { - d.ID = influxdb.ID(rand.Int()) + d.ID = platform.ID(rand.Int()) return nil } return []ServiceSetterFn{WithDashboardSVC(fakeDashSVC)} @@ -1287,8 +1290,8 @@ func TestService(t *testing.T) { t.Run("maps notification endpoints with labels", func(t *testing.T) { opts := func() []ServiceSetterFn { fakeEndpointSVC := mock.NewNotificationEndpointService() - fakeEndpointSVC.CreateNotificationEndpointF = func(ctx context.Context, nr influxdb.NotificationEndpoint, userID influxdb.ID) error { - nr.SetID(influxdb.ID(rand.Int())) + fakeEndpointSVC.CreateNotificationEndpointF = func(ctx context.Context, nr influxdb.NotificationEndpoint, userID platform.ID) error { + nr.SetID(platform.ID(rand.Int())) return nil } return []ServiceSetterFn{WithNotificationEndpointSVC(fakeEndpointSVC)} @@ -1306,8 +1309,8 @@ func TestService(t *testing.T) { t.Run("maps notification rules with labels", func(t *testing.T) { opts := func() []ServiceSetterFn { fakeRuleStore := mock.NewNotificationRuleStore() - fakeRuleStore.CreateNotificationRuleF = func(ctx context.Context, nr influxdb.NotificationRuleCreate, userID influxdb.ID) error { - nr.SetID(influxdb.ID(fakeRuleStore.CreateNotificationRuleCalls.Count() + 1)) + fakeRuleStore.CreateNotificationRuleF = func(ctx context.Context, nr influxdb.NotificationRuleCreate, userID platform.ID) error { + nr.SetID(platform.ID(fakeRuleStore.CreateNotificationRuleCalls.Count() + 1)) return nil } return []ServiceSetterFn{ @@ -1334,7 +1337,7 @@ func TestService(t *testing.T) { return nil, errors.New("bad flux query provided: " + tc.Flux) } return &influxdb.Task{ - ID: influxdb.ID(rand.Int()), + ID: platform.ID(rand.Int()), Type: tc.Type, OrganizationID: tc.OrganizationID, OwnerID: tc.OwnerID, @@ -1359,8 +1362,8 @@ func TestService(t *testing.T) { t.Run("maps telegrafs with labels", func(t *testing.T) { opts := func() []ServiceSetterFn { fakeTeleSVC := mock.NewTelegrafConfigStore() - fakeTeleSVC.CreateTelegrafConfigF = func(_ context.Context, cfg *influxdb.TelegrafConfig, _ influxdb.ID) error { - cfg.ID = influxdb.ID(rand.Int()) + fakeTeleSVC.CreateTelegrafConfigF = func(_ context.Context, cfg *influxdb.TelegrafConfig, _ platform.ID) error { + cfg.ID = platform.ID(rand.Int()) return nil } return []ServiceSetterFn{WithTelegrafSVC(fakeTeleSVC)} @@ -1379,7 +1382,7 @@ func TestService(t *testing.T) { opt := func() []ServiceSetterFn { fakeVarSVC := mock.NewVariableService() fakeVarSVC.CreateVariableF = func(_ context.Context, v *influxdb.Variable) error { - v.ID = influxdb.ID(rand.Int()) + v.ID = platform.ID(rand.Int()) return nil } return []ServiceSetterFn{WithVariableSVC(fakeVarSVC)} @@ -1399,14 +1402,14 @@ func TestService(t *testing.T) { t.Run("successfully creates template of endpoints", func(t *testing.T) { testfileRunner(t, "testdata/notification_endpoint.yml", func(t *testing.T, template *Template) { fakeEndpointSVC := mock.NewNotificationEndpointService() - fakeEndpointSVC.CreateNotificationEndpointF = func(ctx context.Context, nr influxdb.NotificationEndpoint, userID influxdb.ID) error { - nr.SetID(influxdb.ID(fakeEndpointSVC.CreateNotificationEndpointCalls.Count() + 1)) + fakeEndpointSVC.CreateNotificationEndpointF = func(ctx context.Context, nr influxdb.NotificationEndpoint, userID platform.ID) error { + nr.SetID(platform.ID(fakeEndpointSVC.CreateNotificationEndpointCalls.Count() + 1)) return nil } svc := newTestService(WithNotificationEndpointSVC(fakeEndpointSVC)) - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) impact, err := svc.Apply(context.TODO(), orgID, 0, ApplyWithTemplate(template)) require.NoError(t, err) @@ -1445,8 +1448,8 @@ func TestService(t *testing.T) { t.Run("rolls back all created notifications on an error", func(t *testing.T) { testfileRunner(t, "testdata/notification_endpoint.yml", func(t *testing.T, template *Template) { fakeEndpointSVC := mock.NewNotificationEndpointService() - fakeEndpointSVC.CreateNotificationEndpointF = func(ctx context.Context, nr influxdb.NotificationEndpoint, userID influxdb.ID) error { - nr.SetID(influxdb.ID(fakeEndpointSVC.CreateNotificationEndpointCalls.Count() + 1)) + fakeEndpointSVC.CreateNotificationEndpointF = func(ctx context.Context, nr influxdb.NotificationEndpoint, userID platform.ID) error { + nr.SetID(platform.ID(fakeEndpointSVC.CreateNotificationEndpointCalls.Count() + 1)) if fakeEndpointSVC.CreateNotificationEndpointCalls.Count() == 3 { return errors.New("hit that kill count") } @@ -1455,7 +1458,7 @@ func TestService(t *testing.T) { svc := newTestService(WithNotificationEndpointSVC(fakeEndpointSVC)) - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) _, err := svc.Apply(context.TODO(), orgID, 0, ApplyWithTemplate(template)) require.Error(t, err) @@ -1469,13 +1472,13 @@ func TestService(t *testing.T) { t.Run("successfully creates", func(t *testing.T) { testfileRunner(t, "testdata/notification_rule.yml", func(t *testing.T, template *Template) { fakeEndpointSVC := mock.NewNotificationEndpointService() - fakeEndpointSVC.CreateNotificationEndpointF = func(ctx context.Context, nr influxdb.NotificationEndpoint, userID influxdb.ID) error { - nr.SetID(influxdb.ID(fakeEndpointSVC.CreateNotificationEndpointCalls.Count() + 1)) + fakeEndpointSVC.CreateNotificationEndpointF = func(ctx context.Context, nr influxdb.NotificationEndpoint, userID platform.ID) error { + nr.SetID(platform.ID(fakeEndpointSVC.CreateNotificationEndpointCalls.Count() + 1)) return nil } fakeRuleStore := mock.NewNotificationRuleStore() - fakeRuleStore.CreateNotificationRuleF = func(ctx context.Context, nr influxdb.NotificationRuleCreate, userID influxdb.ID) error { - nr.SetID(influxdb.ID(fakeRuleStore.CreateNotificationRuleCalls.Count() + 1)) + fakeRuleStore.CreateNotificationRuleF = func(ctx context.Context, nr influxdb.NotificationRuleCreate, userID platform.ID) error { + nr.SetID(platform.ID(fakeRuleStore.CreateNotificationRuleCalls.Count() + 1)) return nil } @@ -1484,7 +1487,7 @@ func TestService(t *testing.T) { WithNotificationRuleSVC(fakeRuleStore), ) - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) impact, err := svc.Apply(context.TODO(), orgID, 0, ApplyWithTemplate(template)) require.NoError(t, err) @@ -1503,11 +1506,11 @@ func TestService(t *testing.T) { t.Run("rolls back all created notification rules on an error", func(t *testing.T) { testfileRunner(t, "testdata/notification_rule.yml", func(t *testing.T, template *Template) { fakeRuleStore := mock.NewNotificationRuleStore() - fakeRuleStore.CreateNotificationRuleF = func(ctx context.Context, nr influxdb.NotificationRuleCreate, userID influxdb.ID) error { - nr.SetID(influxdb.ID(fakeRuleStore.CreateNotificationRuleCalls.Count() + 1)) + fakeRuleStore.CreateNotificationRuleF = func(ctx context.Context, nr influxdb.NotificationRuleCreate, userID platform.ID) error { + nr.SetID(platform.ID(fakeRuleStore.CreateNotificationRuleCalls.Count() + 1)) return nil } - fakeRuleStore.DeleteNotificationRuleF = func(ctx context.Context, id influxdb.ID) error { + fakeRuleStore.DeleteNotificationRuleF = func(ctx context.Context, id platform.ID) error { if id != 1 { return errors.New("wrong id here") } @@ -1515,7 +1518,7 @@ func TestService(t *testing.T) { } fakeLabelSVC := mock.NewLabelService() fakeLabelSVC.CreateLabelFn = func(ctx context.Context, l *influxdb.Label) error { - l.ID = influxdb.ID(fakeLabelSVC.CreateLabelCalls.Count() + 1) + l.ID = platform.ID(fakeLabelSVC.CreateLabelCalls.Count() + 1) return nil } fakeLabelSVC.CreateLabelMappingFn = func(ctx context.Context, m *influxdb.LabelMapping) error { @@ -1527,7 +1530,7 @@ func TestService(t *testing.T) { WithNotificationRuleSVC(fakeRuleStore), ) - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) _, err := svc.Apply(context.TODO(), orgID, 0, ApplyWithTemplate(template)) require.Error(t, err) @@ -1540,7 +1543,7 @@ func TestService(t *testing.T) { t.Run("tasks", func(t *testing.T) { t.Run("successfuly creates", func(t *testing.T) { testfileRunner(t, "testdata/tasks.yml", func(t *testing.T, template *Template) { - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) fakeTaskSVC := mock.NewTaskService() fakeTaskSVC.CreateTaskFn = func(ctx context.Context, tc influxdb.TaskCreate) (*influxdb.Task, error) { @@ -1550,7 +1553,7 @@ func TestService(t *testing.T) { return nil, errors.New("bad flux query provided: " + tc.Flux) } return &influxdb.Task{ - ID: influxdb.ID(fakeTaskSVC.CreateTaskCalls.Count() + 1), + ID: platform.ID(fakeTaskSVC.CreateTaskCalls.Count() + 1), Type: tc.Type, OrganizationID: tc.OrganizationID, OwnerID: tc.OwnerID, @@ -1588,13 +1591,13 @@ func TestService(t *testing.T) { return nil, errors.New("expected error") } return &influxdb.Task{ - ID: influxdb.ID(fakeTaskSVC.CreateTaskCalls.Count() + 1), + ID: platform.ID(fakeTaskSVC.CreateTaskCalls.Count() + 1), }, nil } svc := newTestService(WithTaskSVC(fakeTaskSVC)) - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) _, err := svc.Apply(context.TODO(), orgID, 0, ApplyWithTemplate(template)) require.Error(t, err) @@ -1607,10 +1610,10 @@ func TestService(t *testing.T) { t.Run("telegrafs", func(t *testing.T) { t.Run("successfuly creates", func(t *testing.T) { testfileRunner(t, "testdata/telegraf.yml", func(t *testing.T, template *Template) { - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) fakeTeleSVC := mock.NewTelegrafConfigStore() - fakeTeleSVC.CreateTelegrafConfigF = func(_ context.Context, tc *influxdb.TelegrafConfig, userID influxdb.ID) error { + fakeTeleSVC.CreateTelegrafConfigF = func(_ context.Context, tc *influxdb.TelegrafConfig, userID platform.ID) error { tc.ID = 1 return nil } @@ -1631,15 +1634,15 @@ func TestService(t *testing.T) { t.Run("rolls back all created telegrafs on an error", func(t *testing.T) { testfileRunner(t, "testdata/telegraf.yml", func(t *testing.T, template *Template) { fakeTeleSVC := mock.NewTelegrafConfigStore() - fakeTeleSVC.CreateTelegrafConfigF = func(_ context.Context, tc *influxdb.TelegrafConfig, userID influxdb.ID) error { + fakeTeleSVC.CreateTelegrafConfigF = func(_ context.Context, tc *influxdb.TelegrafConfig, userID platform.ID) error { t.Log("called") if fakeTeleSVC.CreateTelegrafConfigCalls.Count() == 1 { return errors.New("limit hit") } - tc.ID = influxdb.ID(1) + tc.ID = platform.ID(1) return nil } - fakeTeleSVC.DeleteTelegrafConfigF = func(_ context.Context, id influxdb.ID) error { + fakeTeleSVC.DeleteTelegrafConfigF = func(_ context.Context, id platform.ID) error { if id != 1 { return errors.New("wrong id here") } @@ -1648,7 +1651,7 @@ func TestService(t *testing.T) { svc := newTestService(WithTelegrafSVC(fakeTeleSVC)) - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) _, err := svc.Apply(context.TODO(), orgID, 0, ApplyWithTemplate(template)) require.Error(t, err) @@ -1663,13 +1666,13 @@ func TestService(t *testing.T) { testfileRunner(t, "testdata/variables.yml", func(t *testing.T, template *Template) { fakeVarSVC := mock.NewVariableService() fakeVarSVC.CreateVariableF = func(_ context.Context, v *influxdb.Variable) error { - v.ID = influxdb.ID(fakeVarSVC.CreateVariableCalls.Count() + 1) + v.ID = platform.ID(fakeVarSVC.CreateVariableCalls.Count() + 1) return nil } svc := newTestService(WithVariableSVC(fakeVarSVC)) - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) impact, err := svc.Apply(context.TODO(), orgID, 0, ApplyWithTemplate(template)) require.NoError(t, err) @@ -1707,7 +1710,7 @@ func TestService(t *testing.T) { svc := newTestService(WithVariableSVC(fakeVarSVC)) - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) _, err := svc.Apply(context.TODO(), orgID, 0, ApplyWithTemplate(template)) require.Error(t, err) @@ -1718,14 +1721,14 @@ func TestService(t *testing.T) { t.Run("will not apply variable if no changes to be applied", func(t *testing.T) { testfileRunner(t, "testdata/variables.yml", func(t *testing.T, template *Template) { - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) fakeVarSVC := mock.NewVariableService() fakeVarSVC.FindVariablesF = func(ctx context.Context, f influxdb.VariableFilter, _ ...influxdb.FindOptions) ([]*influxdb.Variable, error) { return []*influxdb.Variable{ { // makes all template changes same as they are on the existing - ID: influxdb.ID(1), + ID: platform.ID(1), OrganizationID: orgID, Name: template.mVariables["var-const-3"].Name(), Arguments: &influxdb.VariableArguments{ @@ -1741,8 +1744,8 @@ func TestService(t *testing.T) { } return nil } - fakeVarSVC.UpdateVariableF = func(_ context.Context, id influxdb.ID, v *influxdb.VariableUpdate) (*influxdb.Variable, error) { - if id > influxdb.ID(1) { + fakeVarSVC.UpdateVariableF = func(_ context.Context, id platform.ID, v *influxdb.VariableUpdate) (*influxdb.Variable, error) { + if id > platform.ID(1) { return nil, errors.New("this id should not be updated") } return &influxdb.Variable{ID: id}, nil @@ -1768,7 +1771,7 @@ func TestService(t *testing.T) { t.Run("Export", func(t *testing.T) { newThresholdBase := func(i int) icheck.Base { return icheck.Base{ - ID: influxdb.ID(i), + ID: platform.ID(i), TaskID: 300, Name: fmt.Sprintf("check_%d", i), Description: fmt.Sprintf("desc_%d", i), @@ -1828,7 +1831,7 @@ func TestService(t *testing.T) { } bktSVC := mock.NewBucketService() - bktSVC.FindBucketByIDFn = func(_ context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + bktSVC.FindBucketByIDFn = func(_ context.Context, id platform.ID) (*influxdb.Bucket, error) { if id != expected.ID { return nil, errors.New("uh ohhh, wrong id here: " + id.String()) } @@ -1877,19 +1880,19 @@ func TestService(t *testing.T) { t.Run("bucket by name", func(t *testing.T) { knownBuckets := []*influxdb.Bucket{ { - ID: influxdb.ID(1), + ID: platform.ID(1), Name: "bucket", Description: "desc", RetentionPeriod: time.Hour, }, { - ID: influxdb.ID(2), + ID: platform.ID(2), Name: "bucketCopy", Description: "desc", RetentionPeriod: time.Hour, }, { - ID: influxdb.ID(3), + ID: platform.ID(3), Name: "bucket3", Description: "desc", RetentionPeriod: time.Hour, @@ -1899,7 +1902,7 @@ func TestService(t *testing.T) { tests := []struct { name string findName string - findID influxdb.ID + findID platform.ID expected []*influxdb.Bucket }{ { @@ -1914,13 +1917,13 @@ func TestService(t *testing.T) { }, { name: "find bucket by id", - findID: influxdb.ID(2), + findID: platform.ID(2), expected: []*influxdb.Bucket{knownBuckets[1]}, }, { // todo: verify this is intended behavior (it is in swagger) name: "find by id, set new name", - findID: influxdb.ID(2), + findID: platform.ID(2), findName: "renamedBucket", expected: []*influxdb.Bucket{knownBuckets[1]}, }, @@ -1961,7 +1964,7 @@ func TestService(t *testing.T) { if tt.findName != "" { resToClone.Name = tt.findName } - if tt.findID != influxdb.ID(0) { + if tt.findID != platform.ID(0) { resToClone.ID = tt.findID } @@ -1975,7 +1978,7 @@ func TestService(t *testing.T) { } else { require.NoError(t, err) - if tt.findName != "" && tt.findID != influxdb.ID(0) { + if tt.findName != "" && tt.findID != platform.ID(0) { tt.expected[0].Name = tt.findName } @@ -2057,11 +2060,11 @@ func TestService(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { - id := influxdb.ID(1) + id := platform.ID(1) tt.expected.SetID(id) checkSVC := mock.NewCheckService() - checkSVC.FindCheckByIDFn = func(ctx context.Context, id influxdb.ID) (influxdb.Check, error) { + checkSVC.FindCheckByIDFn = func(ctx context.Context, id platform.ID) (influxdb.Check, error) { if id != tt.expected.GetID() { return nil, errors.New("uh ohhh, wrong id here: " + id.String()) } @@ -2153,7 +2156,7 @@ func TestService(t *testing.T) { }, &icheck.Deadman{ Base: icheck.Base{ - ID: influxdb.ID(2), + ID: platform.ID(2), TaskID: 300, Name: "check_1", Description: "desc_2", @@ -2178,7 +2181,7 @@ func TestService(t *testing.T) { tests := []struct { name string findName string - findID influxdb.ID + findID platform.ID expected []influxdb.Check }{ { @@ -2198,12 +2201,12 @@ func TestService(t *testing.T) { }, { name: "find check by id", - findID: influxdb.ID(1), + findID: platform.ID(1), expected: []influxdb.Check{knownChecks[1]}, }, { name: "find check by id, set new name", - findID: influxdb.ID(1), + findID: platform.ID(1), findName: "chex original", expected: []influxdb.Check{knownChecks[1]}, }, @@ -2245,7 +2248,7 @@ func TestService(t *testing.T) { if tt.findName != "" { resToClone.Name = tt.findName } - if tt.findID != influxdb.ID(0) { + if tt.findID != platform.ID(0) { resToClone.ID = tt.findID } @@ -2256,7 +2259,7 @@ func TestService(t *testing.T) { } else { require.NoError(t, err) - if tt.findName != "" && tt.findID != influxdb.ID(0) { + if tt.findName != "" && tt.findID != platform.ID(0) { tt.expected[0].SetName(tt.findName) } @@ -2776,7 +2779,7 @@ func TestService(t *testing.T) { } dashSVC := mock.NewDashboardService() - dashSVC.FindDashboardByIDF = func(_ context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { + dashSVC.FindDashboardByIDF = func(_ context.Context, id platform.ID) (*influxdb.Dashboard, error) { if id != expected.ID { return nil, errors.New("uh ohhh, wrong id here: " + id.String()) } @@ -2791,7 +2794,7 @@ func TestService(t *testing.T) { } return []*influxdb.Dashboard{expected}, 1, nil } - dashSVC.GetDashboardCellViewF = func(_ context.Context, id influxdb.ID, cID influxdb.ID) (*influxdb.View, error) { + dashSVC.GetDashboardCellViewF = func(_ context.Context, id platform.ID, cID platform.ID) (*influxdb.View, error) { if id == expected.ID && cID == expectedCell.ID { return &tt.expectedView, nil } @@ -2835,7 +2838,7 @@ func TestService(t *testing.T) { t.Run("handles duplicate dashboard names", func(t *testing.T) { dashSVC := mock.NewDashboardService() - dashSVC.FindDashboardByIDF = func(_ context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { + dashSVC.FindDashboardByIDF = func(_ context.Context, id platform.ID) (*influxdb.Dashboard, error) { return &influxdb.Dashboard{ ID: id, Name: "dash name", @@ -2886,7 +2889,7 @@ func TestService(t *testing.T) { newDash := func(name string, view influxdb.View) *influxdb.Dashboard { id++ return &influxdb.Dashboard{ - ID: influxdb.ID(id), + ID: platform.ID(id), Name: name, Description: fmt.Sprintf("desc_%d", id), Cells: []*influxdb.Cell{ @@ -2974,7 +2977,7 @@ func TestService(t *testing.T) { tests := []struct { name string findName string - findID influxdb.ID + findID platform.ID expected []*influxdb.Dashboard }{ { @@ -3022,7 +3025,7 @@ func TestService(t *testing.T) { return knownDashboards, len(knownDashboards), nil } - dashSVC.GetDashboardCellViewF = func(_ context.Context, id influxdb.ID, cID influxdb.ID) (*influxdb.View, error) { + dashSVC.GetDashboardCellViewF = func(_ context.Context, id platform.ID, cID platform.ID) (*influxdb.View, error) { for i := range knownDashboards { if knownDashboards[i].ID == id { return knownDashboards[i].Cells[0].View, nil @@ -3038,7 +3041,7 @@ func TestService(t *testing.T) { if tt.findName != "" { resToClone.Name = tt.findName } - if tt.findID != influxdb.ID(0) { + if tt.findID != platform.ID(0) { resToClone.ID = tt.findID } @@ -3052,7 +3055,7 @@ func TestService(t *testing.T) { } else { require.NoError(t, err) - if tt.findName != "" && tt.findID != influxdb.ID(0) { + if tt.findName != "" && tt.findID != platform.ID(0) { tt.expected[0].Name = tt.findName } @@ -3108,7 +3111,7 @@ func TestService(t *testing.T) { } labelSVC := mock.NewLabelService() - labelSVC.FindLabelByIDFn = func(_ context.Context, id influxdb.ID) (*influxdb.Label, error) { + labelSVC.FindLabelByIDFn = func(_ context.Context, id platform.ID) (*influxdb.Label, error) { if id != expectedLabel.ID { return nil, errors.New("uh ohhh, wrong id here: " + id.String()) } @@ -3171,7 +3174,7 @@ func TestService(t *testing.T) { tests := []struct { name string findName string - findID influxdb.ID + findID platform.ID expected []*influxdb.Label }{ { @@ -3186,13 +3189,13 @@ func TestService(t *testing.T) { }, { name: "find label by id", - findID: influxdb.ID(2), + findID: platform.ID(2), expected: []*influxdb.Label{knownLabels[1]}, }, { name: "find label by id, set new name", findName: "label three", - findID: influxdb.ID(2), + findID: platform.ID(2), expected: []*influxdb.Label{knownLabels[1]}, }, } @@ -3200,7 +3203,7 @@ func TestService(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { labelSVC := mock.NewLabelService() - labelSVC.FindLabelByIDFn = func(_ context.Context, id influxdb.ID) (*influxdb.Label, error) { + labelSVC.FindLabelByIDFn = func(_ context.Context, id platform.ID) (*influxdb.Label, error) { for i := range knownLabels { if knownLabels[i].ID == id { return knownLabels[i], nil @@ -3229,7 +3232,7 @@ func TestService(t *testing.T) { if tt.findName != "" { resToClone.Name = tt.findName } - if tt.findID != influxdb.ID(0) { + if tt.findID != platform.ID(0) { resToClone.ID = tt.findID } @@ -3240,7 +3243,7 @@ func TestService(t *testing.T) { } else { require.NoError(t, err) - if tt.findName != "" && tt.findID != influxdb.ID(0) { + if tt.findName != "" && tt.findID != platform.ID(0) { tt.expected[0].Name = tt.findName } @@ -3349,11 +3352,11 @@ func TestService(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { - id := influxdb.ID(1) + id := platform.ID(1) tt.expected.SetID(id) endpointSVC := mock.NewNotificationEndpointService() - endpointSVC.FindNotificationEndpointByIDF = func(ctx context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { + endpointSVC.FindNotificationEndpointByIDF = func(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { if id != tt.expected.GetID() { return nil, errors.New("uh ohhh, wrong id here: " + id.String()) } @@ -3432,7 +3435,7 @@ func TestService(t *testing.T) { tests := []struct { name string findName string - findID influxdb.ID + findID platform.ID expected []influxdb.NotificationEndpoint }{ { @@ -3447,12 +3450,12 @@ func TestService(t *testing.T) { }, { name: "find notification endpoint by id", - findID: influxdb.ID(2), + findID: platform.ID(2), expected: []influxdb.NotificationEndpoint{knownEndpoints[1]}, }, { name: "find by id, set new name", - findID: influxdb.ID(3), + findID: platform.ID(3), findName: "slack-endpoint", expected: []influxdb.NotificationEndpoint{knownEndpoints[2]}, }, @@ -3461,7 +3464,7 @@ func TestService(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { endpointSVC := mock.NewNotificationEndpointService() - endpointSVC.FindNotificationEndpointByIDF = func(ctx context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { + endpointSVC.FindNotificationEndpointByIDF = func(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { for i := range knownEndpoints { if knownEndpoints[i].GetID() == id { return knownEndpoints[i], nil @@ -3490,7 +3493,7 @@ func TestService(t *testing.T) { if tt.findName != "" { resToClone.Name = tt.findName } - if tt.findID != influxdb.ID(0) { + if tt.findID != platform.ID(0) { resToClone.ID = tt.findID } @@ -3501,7 +3504,7 @@ func TestService(t *testing.T) { } else { require.NoError(t, err) - if tt.findName != "" && tt.findID != influxdb.ID(0) { + if tt.findName != "" && tt.findID != platform.ID(0) { tt.expected[0].SetName(tt.findName) } @@ -3525,10 +3528,10 @@ func TestService(t *testing.T) { t.Run("notification rules", func(t *testing.T) { newRuleBase := func(id int) rule.Base { return rule.Base{ - ID: influxdb.ID(id), + ID: platform.ID(id), Name: "old_name", Description: "desc", - EndpointID: influxdb.ID(id), + EndpointID: platform.ID(id), Every: mustDuration(t, time.Hour), Offset: mustDuration(t, time.Minute), TagRules: []notification.TagRule{ @@ -3606,14 +3609,14 @@ func TestService(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { endpointSVC := mock.NewNotificationEndpointService() - endpointSVC.FindNotificationEndpointByIDF = func(ctx context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { + endpointSVC.FindNotificationEndpointByIDF = func(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { if id != tt.endpoint.GetID() { return nil, errors.New("uh ohhh, wrong id here: " + id.String()) } return tt.endpoint, nil } ruleSVC := mock.NewNotificationRuleStore() - ruleSVC.FindNotificationRuleByIDF = func(ctx context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { + ruleSVC.FindNotificationRuleByIDF = func(ctx context.Context, id platform.ID) (influxdb.NotificationRule, error) { return tt.rule, nil } ruleSVC.FindNotificationRulesF = func(ctx context.Context, _ influxdb.NotificationRuleFilter, _ ...influxdb.FindOptions) ([]influxdb.NotificationRule, int, error) { @@ -3696,7 +3699,7 @@ func TestService(t *testing.T) { t.Run("handles rules duplicate names", func(t *testing.T) { endpointSVC := mock.NewNotificationEndpointService() - endpointSVC.FindNotificationEndpointByIDF = func(ctx context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { + endpointSVC.FindNotificationEndpointByIDF = func(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { return &endpoint.HTTP{ Base: endpoint.Base{ ID: &id, @@ -3710,7 +3713,7 @@ func TestService(t *testing.T) { }, nil } ruleSVC := mock.NewNotificationRuleStore() - ruleSVC.FindNotificationRuleByIDF = func(ctx context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { + ruleSVC.FindNotificationRuleByIDF = func(ctx context.Context, id platform.ID) (influxdb.NotificationRule, error) { return &rule.HTTP{ Base: newRuleBase(int(id)), }, nil @@ -3758,10 +3761,10 @@ func TestService(t *testing.T) { t.Run("notification rules by name", func(t *testing.T) { newRuleBase := func(id int, name string) rule.Base { return rule.Base{ - ID: influxdb.ID(id), + ID: platform.ID(id), Name: name, Description: fmt.Sprintf("desc %d", id), - EndpointID: influxdb.ID(1), // todo: setting to id as well likely doesn't work due to safeID + EndpointID: platform.ID(1), // todo: setting to id as well likely doesn't work due to safeID Every: mustDuration(t, time.Hour), Offset: mustDuration(t, time.Minute), TagRules: []notification.TagRule{ @@ -3793,7 +3796,7 @@ func TestService(t *testing.T) { tests := []struct { name string findName string - findID influxdb.ID + findID platform.ID expected []influxdb.NotificationRule }{ { @@ -3813,12 +3816,12 @@ func TestService(t *testing.T) { }, { name: "find rule by id", - findID: influxdb.ID(2), + findID: platform.ID(2), expected: []influxdb.NotificationRule{knownRules[1]}, }, { name: "find by id, set new name", - findID: influxdb.ID(3), + findID: platform.ID(3), findName: "slack-notify", expected: []influxdb.NotificationRule{knownRules[2]}, }, @@ -3827,7 +3830,7 @@ func TestService(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { endpointSVC := mock.NewNotificationEndpointService() - endpointSVC.FindNotificationEndpointByIDF = func(ctx context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { + endpointSVC.FindNotificationEndpointByIDF = func(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { for i := range knownEndpoints { if knownEndpoints[i].GetID() == id { return knownEndpoints[i], nil @@ -3838,7 +3841,7 @@ func TestService(t *testing.T) { } ruleSVC := mock.NewNotificationRuleStore() - ruleSVC.FindNotificationRuleByIDF = func(ctx context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { + ruleSVC.FindNotificationRuleByIDF = func(ctx context.Context, id platform.ID) (influxdb.NotificationRule, error) { for i := range knownRules { if knownRules[i].GetID() == id { return knownRules[i], nil @@ -3857,7 +3860,7 @@ func TestService(t *testing.T) { if tt.findName != "" { resToClone.Name = tt.findName } - if tt.findID != influxdb.ID(0) { + if tt.findID != platform.ID(0) { resToClone.ID = tt.findID } @@ -3881,7 +3884,7 @@ func TestService(t *testing.T) { return actual.NotificationEndpoints[i].NotificationEndpoint.GetDescription() < actual.NotificationEndpoints[j].NotificationEndpoint.GetDescription() }) - if tt.findName != "" && tt.findID != influxdb.ID(0) { + if tt.findName != "" && tt.findID != platform.ID(0) { tt.expected[0].SetName(tt.findName) } @@ -3976,7 +3979,7 @@ func TestService(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { taskSVC := mock.NewTaskService() - taskSVC.FindTaskByIDFn = func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + taskSVC.FindTaskByIDFn = func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { if id != tt.task.ID { return nil, errors.New("wrong id provided: " + id.String()) } @@ -4023,7 +4026,7 @@ func TestService(t *testing.T) { t.Run("handles multiple tasks of same name", func(t *testing.T) { taskSVC := mock.NewTaskService() - taskSVC.FindTaskByIDFn = func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + taskSVC.FindTaskByIDFn = func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { return &influxdb.Task{ ID: id, Type: influxdb.TaskSystemType, @@ -4099,7 +4102,7 @@ func TestService(t *testing.T) { tests := []struct { name string findName string - findID influxdb.ID + findID platform.ID expected []*influxdb.Task }{ { @@ -4119,12 +4122,12 @@ func TestService(t *testing.T) { }, { name: "find task by id", - findID: influxdb.ID(2), + findID: platform.ID(2), expected: []*influxdb.Task{knownTasks[1]}, }, { name: "find by id, set new name", - findID: influxdb.ID(2), + findID: platform.ID(2), findName: "renamedTask", expected: []*influxdb.Task{knownTasks[1]}, }, @@ -4133,7 +4136,7 @@ func TestService(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { taskSVC := mock.NewTaskService() - taskSVC.FindTaskByIDFn = func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + taskSVC.FindTaskByIDFn = func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { for i := range knownTasks { if knownTasks[i].ID == id { return knownTasks[i], nil @@ -4158,7 +4161,7 @@ func TestService(t *testing.T) { if tt.findName != "" { resToClone.Name = tt.findName } - if tt.findID != influxdb.ID(0) { + if tt.findID != platform.ID(0) { resToClone.ID = tt.findID } @@ -4169,7 +4172,7 @@ func TestService(t *testing.T) { } else { require.NoError(t, err) - if tt.findName != "" && tt.findID != influxdb.ID(0) { + if tt.findName != "" && tt.findID != platform.ID(0) { tt.expected[0].Name = tt.findName } @@ -4204,7 +4207,7 @@ func TestService(t *testing.T) { Config: "some config string", } teleStore := mock.NewTelegrafConfigStore() - teleStore.FindTelegrafConfigByIDF = func(ctx context.Context, id influxdb.ID) (*influxdb.TelegrafConfig, error) { + teleStore.FindTelegrafConfigByIDF = func(ctx context.Context, id platform.ID) (*influxdb.TelegrafConfig, error) { tConfig.ID = id return tConfig, nil } @@ -4282,7 +4285,7 @@ func TestService(t *testing.T) { tests := []struct { name string findName string - findID influxdb.ID + findID platform.ID expected []*influxdb.TelegrafConfig }{ { @@ -4302,12 +4305,12 @@ func TestService(t *testing.T) { }, { name: "find telegraf by id", - findID: influxdb.ID(2), + findID: platform.ID(2), expected: []*influxdb.TelegrafConfig{knownConfigs[1]}, }, { name: "find by id, set new name", - findID: influxdb.ID(2), + findID: platform.ID(2), findName: "newConfig", expected: []*influxdb.TelegrafConfig{knownConfigs[1]}, }, @@ -4316,7 +4319,7 @@ func TestService(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { teleStore := mock.NewTelegrafConfigStore() - teleStore.FindTelegrafConfigByIDF = func(_ context.Context, id influxdb.ID) (*influxdb.TelegrafConfig, error) { + teleStore.FindTelegrafConfigByIDF = func(_ context.Context, id platform.ID) (*influxdb.TelegrafConfig, error) { for i := range knownConfigs { if knownConfigs[i].ID == id { return knownConfigs[i], nil @@ -4334,7 +4337,7 @@ func TestService(t *testing.T) { if tt.findName != "" { resToClone.Name = tt.findName } - if tt.findID != influxdb.ID(0) { + if tt.findID != platform.ID(0) { resToClone.ID = tt.findID } @@ -4345,7 +4348,7 @@ func TestService(t *testing.T) { } else { require.NoError(t, err) - if tt.findName != "" && tt.findID != influxdb.ID(0) { + if tt.findName != "" && tt.findID != platform.ID(0) { tt.expected[0].Name = tt.findName } @@ -4432,7 +4435,7 @@ func TestService(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { varSVC := mock.NewVariableService() - varSVC.FindVariableByIDF = func(_ context.Context, id influxdb.ID) (*influxdb.Variable, error) { + varSVC.FindVariableByIDF = func(_ context.Context, id platform.ID) (*influxdb.Variable, error) { if id != tt.expectedVar.ID { return nil, errors.New("uh ohhh, wrong id here: " + id.String()) } @@ -4509,7 +4512,7 @@ func TestService(t *testing.T) { tests := []struct { name string findName string - findID influxdb.ID + findID platform.ID expected []*influxdb.Variable }{ { @@ -4524,12 +4527,12 @@ func TestService(t *testing.T) { }, { name: "find variable by id", - findID: influxdb.ID(2), + findID: platform.ID(2), expected: []*influxdb.Variable{knownVariables[1]}, }, { name: "find by id, set new name", - findID: influxdb.ID(2), + findID: platform.ID(2), findName: "useful var", expected: []*influxdb.Variable{knownVariables[1]}, }, @@ -4538,7 +4541,7 @@ func TestService(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { varSVC := mock.NewVariableService() - varSVC.FindVariableByIDF = func(_ context.Context, id influxdb.ID) (*influxdb.Variable, error) { + varSVC.FindVariableByIDF = func(_ context.Context, id platform.ID) (*influxdb.Variable, error) { for i := range knownVariables { if knownVariables[i].ID == id { return knownVariables[i], nil @@ -4557,7 +4560,7 @@ func TestService(t *testing.T) { if tt.findName != "" { resToClone.Name = tt.findName } - if tt.findID != influxdb.ID(0) { + if tt.findID != platform.ID(0) { resToClone.ID = tt.findID } @@ -4568,7 +4571,7 @@ func TestService(t *testing.T) { } else { require.NoError(t, err) - if tt.findName != "" && tt.findID != influxdb.ID(0) { + if tt.findName != "" && tt.findID != platform.ID(0) { tt.expected[0].Name = tt.findName } @@ -4598,7 +4601,7 @@ func TestService(t *testing.T) { } bktSVC := mock.NewBucketService() - bktSVC.FindBucketByIDFn = func(_ context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + bktSVC.FindBucketByIDFn = func(_ context.Context, id platform.ID) (*influxdb.Bucket, error) { if id != expected.ID { return nil, errors.New("uh ohhh, wrong id here: " + id.String()) } @@ -4651,7 +4654,7 @@ func TestService(t *testing.T) { t.Run("multiple resources with same associations", func(t *testing.T) { bktSVC := mock.NewBucketService() - bktSVC.FindBucketByIDFn = func(_ context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + bktSVC.FindBucketByIDFn = func(_ context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ID: id, Name: strconv.Itoa(int(id))}, nil } @@ -4713,7 +4716,7 @@ func TestService(t *testing.T) { t.Run("labels do not fetch associations", func(t *testing.T) { labelSVC := mock.NewLabelService() - labelSVC.FindLabelByIDFn = func(_ context.Context, id influxdb.ID) (*influxdb.Label, error) { + labelSVC.FindLabelByIDFn = func(_ context.Context, id platform.ID) (*influxdb.Label, error) { return &influxdb.Label{ID: id, Name: "label_1"}, nil } labelSVC.FindResourceLabelsFn = func(_ context.Context, f influxdb.LabelMappingFilter) ([]*influxdb.Label, error) { @@ -4739,7 +4742,7 @@ func TestService(t *testing.T) { }) t.Run("with org id", func(t *testing.T) { - orgID := influxdb.ID(9000) + orgID := platform.ID(9000) bkt := &influxdb.Bucket{ID: 1, Name: "bucket"} bktSVC := mock.NewBucketService() @@ -4749,7 +4752,7 @@ func TestService(t *testing.T) { } return []*influxdb.Bucket{bkt}, 1, nil } - bktSVC.FindBucketByIDFn = func(_ context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + bktSVC.FindBucketByIDFn = func(_ context.Context, id platform.ID) (*influxdb.Bucket, error) { if id != 1 { return nil, errors.New("wrong id") } @@ -4770,7 +4773,7 @@ func TestService(t *testing.T) { } return []influxdb.Check{expectedCheck}, 1, nil } - checkSVC.FindCheckByIDFn = func(ctx context.Context, id influxdb.ID) (influxdb.Check, error) { + checkSVC.FindCheckByIDFn = func(ctx context.Context, id platform.ID) (influxdb.Check, error) { return expectedCheck, nil } @@ -4788,7 +4791,7 @@ func TestService(t *testing.T) { } return []*influxdb.Dashboard{dash}, 1, nil } - dashSVC.FindDashboardByIDF = func(_ context.Context, id influxdb.ID) (*influxdb.Dashboard, error) { + dashSVC.FindDashboardByIDF = func(_ context.Context, id platform.ID) (*influxdb.Dashboard, error) { if id != 2 { return nil, errors.New("wrong id") } @@ -4810,7 +4813,7 @@ func TestService(t *testing.T) { endpointSVC.FindNotificationEndpointsF = func(ctx context.Context, f influxdb.NotificationEndpointFilter, _ ...influxdb.FindOptions) ([]influxdb.NotificationEndpoint, int, error) { return []influxdb.NotificationEndpoint{notificationEndpoint}, 1, nil } - endpointSVC.FindNotificationEndpointByIDF = func(ctx context.Context, id influxdb.ID) (influxdb.NotificationEndpoint, error) { + endpointSVC.FindNotificationEndpointByIDF = func(ctx context.Context, id platform.ID) (influxdb.NotificationEndpoint, error) { return notificationEndpoint, nil } @@ -4828,7 +4831,7 @@ func TestService(t *testing.T) { out := []influxdb.NotificationRule{expectedRule} return out, len(out), nil } - ruleSVC.FindNotificationRuleByIDF = func(ctx context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { + ruleSVC.FindNotificationRuleByIDF = func(ctx context.Context, id platform.ID) (influxdb.NotificationRule, error) { return expectedRule, nil } @@ -4839,7 +4842,7 @@ func TestService(t *testing.T) { } return []*influxdb.Label{{ID: 3, Name: "label"}}, nil } - labelSVC.FindLabelByIDFn = func(_ context.Context, id influxdb.ID) (*influxdb.Label, error) { + labelSVC.FindLabelByIDFn = func(_ context.Context, id platform.ID) (*influxdb.Label, error) { if id != 3 { return nil, errors.New("wrong id") } @@ -4858,7 +4861,7 @@ func TestService(t *testing.T) { {ID: 99}, // this one should be skipped since it is not a system task }, 3, nil } - taskSVC.FindTaskByIDFn = func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + taskSVC.FindTaskByIDFn = func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { if id != 31 { return nil, errors.New("wrong id: " + id.String()) } @@ -4879,7 +4882,7 @@ func TestService(t *testing.T) { } return []*influxdb.Variable{{ID: 4, Name: "variable"}}, nil } - varSVC.FindVariableByIDF = func(_ context.Context, id influxdb.ID) (*influxdb.Variable, error) { + varSVC.FindVariableByIDF = func(_ context.Context, id platform.ID) (*influxdb.Variable, error) { if id != 4 { return nil, errors.New("wrong id") } @@ -4966,7 +4969,7 @@ func TestService(t *testing.T) { stack, err := svc.InitStack(context.Background(), 9000, StackCreate{OrgID: 3333}) require.NoError(t, err) - assert.Equal(t, influxdb.ID(3), stack.ID) + assert.Equal(t, platform.ID(3), stack.ID) assert.Equal(t, now, stack.CreatedAt) assert.Equal(t, now, stack.LatestEvent().UpdatedAt) }) @@ -4980,7 +4983,7 @@ func TestService(t *testing.T) { }{ { name: "unexpected store err", - expectedErrCode: influxdb.EInternal, + expectedErrCode: errors2.EInternal, store: func() *fakeStore { return newFakeStore(func(ctx context.Context, stack Stack) error { return errors.New("unexpected error") @@ -4989,23 +4992,23 @@ func TestService(t *testing.T) { }, { name: "unexpected conflict store err", - expectedErrCode: influxdb.EInternal, + expectedErrCode: errors2.EInternal, store: func() *fakeStore { return newFakeStore(func(ctx context.Context, stack Stack) error { - return &influxdb.Error{Code: influxdb.EConflict} + return &errors2.Error{Code: errors2.EConflict} }) }, }, { name: "org does not exist produces conflict error", - expectedErrCode: influxdb.EConflict, + expectedErrCode: errors2.EConflict, store: func() *fakeStore { return newFakeStore(safeCreateFn) }, orgSVC: func() influxdb.OrganizationService { orgSVC := mock.NewOrganizationService() - orgSVC.FindOrganizationByIDF = func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { - return nil, &influxdb.Error{Code: influxdb.ENotFound} + orgSVC.FindOrganizationByIDF = func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { + return nil, &errors2.Error{Code: errors2.ENotFound} } return orgSVC }, @@ -5028,7 +5031,7 @@ func TestService(t *testing.T) { _, err := svc.InitStack(context.Background(), 9000, StackCreate{OrgID: 3333}) require.Error(t, err) - assert.Equal(t, tt.expectedErrCode, influxdb.ErrorCode(err)) + assert.Equal(t, tt.expectedErrCode, errors2.ErrorCode(err)) } t.Run(tt.name, fn) } @@ -5131,7 +5134,7 @@ func TestService(t *testing.T) { APIVersion: APIVersion, ID: 2, Kind: KindLabel, - MetaName: "collision-1-" + influxdb.ID(333).String()[10:], + MetaName: "collision-1-" + platform.ID(333).String()[10:], }, { APIVersion: APIVersion, @@ -5186,14 +5189,14 @@ func TestService(t *testing.T) { svc := newTestService( WithIDGenerator(mock.IDGenerator{ - IDFn: func() influxdb.ID { + IDFn: func() platform.ID { return 333 }, }), withNameGen(nameGenFn), WithTimeGenerator(newTimeGen(now)), WithStore(&fakeStore{ - readFn: func(ctx context.Context, id influxdb.ID) (Stack, error) { + readFn: func(ctx context.Context, id platform.ID) (Stack, error) { if id != 33 { return Stack{}, errors.New("wrong id: " + id.String()) } @@ -5209,8 +5212,8 @@ func TestService(t *testing.T) { stack, err := svc.UpdateStack(context.Background(), tt.input) require.NoError(t, err) - assert.Equal(t, influxdb.ID(33), stack.ID) - assert.Equal(t, influxdb.ID(3), stack.OrgID) + assert.Equal(t, platform.ID(33), stack.ID) + assert.Equal(t, platform.ID(3), stack.OrgID) assert.Zero(t, stack.CreatedAt) // should always zero value in these tests assert.Equal(t, tt.expected, stack.LatestEvent()) } @@ -5275,8 +5278,8 @@ func Test_normalizeRemoteSources(t *testing.T) { } } -func newTestIDPtr(i int) *influxdb.ID { - id := influxdb.ID(i) +func newTestIDPtr(i int) *platform.ID { + id := platform.ID(i) return &id } @@ -5286,8 +5289,8 @@ func levelPtr(l notification.CheckLevel) *notification.CheckLevel { type fakeStore struct { createFn func(ctx context.Context, stack Stack) error - deleteFn func(ctx context.Context, id influxdb.ID) error - readFn func(ctx context.Context, id influxdb.ID) (Stack, error) + deleteFn func(ctx context.Context, id platform.ID) error + readFn func(ctx context.Context, id platform.ID) (Stack, error) updateFn func(ctx context.Context, stack Stack) error } @@ -5300,11 +5303,11 @@ func (s *fakeStore) CreateStack(ctx context.Context, stack Stack) error { panic("not implemented") } -func (s *fakeStore) ListStacks(ctx context.Context, orgID influxdb.ID, f ListFilter) ([]Stack, error) { +func (s *fakeStore) ListStacks(ctx context.Context, orgID platform.ID, f ListFilter) ([]Stack, error) { panic("not implemented") } -func (s *fakeStore) ReadStackByID(ctx context.Context, id influxdb.ID) (Stack, error) { +func (s *fakeStore) ReadStackByID(ctx context.Context, id platform.ID) (Stack, error) { if s.readFn != nil { return s.readFn(ctx, id) } @@ -5318,22 +5321,22 @@ func (s *fakeStore) UpdateStack(ctx context.Context, stack Stack) error { panic("not implemented") } -func (s *fakeStore) DeleteStack(ctx context.Context, id influxdb.ID) error { +func (s *fakeStore) DeleteStack(ctx context.Context, id platform.ID) error { if s.deleteFn != nil { return s.deleteFn(ctx, id) } panic("not implemented") } -type fakeIDGen func() influxdb.ID +type fakeIDGen func() platform.ID -func newFakeIDGen(id influxdb.ID) fakeIDGen { - return func() influxdb.ID { +func newFakeIDGen(id platform.ID) fakeIDGen { + return func() platform.ID { return id } } -func (f fakeIDGen) ID() influxdb.ID { +func (f fakeIDGen) ID() platform.ID { return f() } diff --git a/pkger/service_tracing.go b/pkger/service_tracing.go index a261393f868..481328089fa 100644 --- a/pkger/service_tracing.go +++ b/pkger/service_tracing.go @@ -3,7 +3,8 @@ package pkger import ( "context" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/tracing" "github.com/opentracing/opentracing-go/log" ) @@ -21,25 +22,25 @@ func MWTracing() SVCMiddleware { var _ SVC = (*traceMW)(nil) -func (s *traceMW) InitStack(ctx context.Context, userID influxdb.ID, newStack StackCreate) (Stack, error) { +func (s *traceMW) InitStack(ctx context.Context, userID platform.ID, newStack StackCreate) (Stack, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() return s.next.InitStack(ctx, userID, newStack) } -func (s *traceMW) UninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) (Stack, error) { +func (s *traceMW) UninstallStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) (Stack, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() return s.next.UninstallStack(ctx, identifiers) } -func (s *traceMW) DeleteStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID influxdb.ID }) error { +func (s *traceMW) DeleteStack(ctx context.Context, identifiers struct{ OrgID, UserID, StackID platform.ID }) error { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() return s.next.DeleteStack(ctx, identifiers) } -func (s *traceMW) ListStacks(ctx context.Context, orgID influxdb.ID, f ListFilter) ([]Stack, error) { +func (s *traceMW) ListStacks(ctx context.Context, orgID platform.ID, f ListFilter) ([]Stack, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -51,7 +52,7 @@ func (s *traceMW) ListStacks(ctx context.Context, orgID influxdb.ID, f ListFilte return stacks, err } -func (s *traceMW) ReadStack(ctx context.Context, id influxdb.ID) (Stack, error) { +func (s *traceMW) ReadStack(ctx context.Context, id platform.ID) (Stack, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() return s.next.ReadStack(ctx, id) @@ -69,14 +70,14 @@ func (s *traceMW) Export(ctx context.Context, opts ...ExportOptFn) (template *Te return s.next.Export(ctx, opts...) } -func (s *traceMW) DryRun(ctx context.Context, orgID, userID influxdb.ID, opts ...ApplyOptFn) (ImpactSummary, error) { +func (s *traceMW) DryRun(ctx context.Context, orgID, userID platform.ID, opts ...ApplyOptFn) (ImpactSummary, error) { span, ctx := tracing.StartSpanFromContext(ctx) span.LogKV("orgID", orgID.String(), "userID", userID.String()) defer span.Finish() return s.next.DryRun(ctx, orgID, userID, opts...) } -func (s *traceMW) Apply(ctx context.Context, orgID, userID influxdb.ID, opts ...ApplyOptFn) (ImpactSummary, error) { +func (s *traceMW) Apply(ctx context.Context, orgID, userID platform.ID, opts ...ApplyOptFn) (ImpactSummary, error) { span, ctx := tracing.StartSpanFromContext(ctx) span.LogKV("orgID", orgID.String(), "userID", userID.String()) defer span.Finish() diff --git a/pkger/store.go b/pkger/store.go index def6ab809fe..6ffc848b257 100644 --- a/pkger/store.go +++ b/pkger/store.go @@ -7,7 +7,9 @@ import ( "sort" "time" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2/kv" ) @@ -80,7 +82,7 @@ func (s *StoreKV) CreateStack(ctx context.Context, stack Stack) error { } // ListStacks returns a list of stacks. -func (s *StoreKV) ListStacks(ctx context.Context, orgID influxdb.ID, f ListFilter) ([]Stack, error) { +func (s *StoreKV) ListStacks(ctx context.Context, orgID platform.ID, f ListFilter) ([]Stack, error) { if len(f.StackIDs) > 0 && len(f.Names) == 0 { return s.listStacksByID(ctx, orgID, f.StackIDs) } @@ -114,7 +116,7 @@ func (s *StoreKV) ListStacks(ctx context.Context, orgID influxdb.ID, f ListFilte return stacks, nil } -func storeListFilterFn(orgID influxdb.ID, f ListFilter) (func(*entStack) bool, error) { +func storeListFilterFn(orgID platform.ID, f ListFilter) (func(*entStack) bool, error) { orgIDEncoded, err := orgID.Encode() if err != nil { return nil, err @@ -155,11 +157,11 @@ func storeListFilterFn(orgID influxdb.ID, f ListFilter) (func(*entStack) bool, e }, nil } -func (s *StoreKV) listStacksByID(ctx context.Context, orgID influxdb.ID, stackIDs []influxdb.ID) ([]Stack, error) { +func (s *StoreKV) listStacksByID(ctx context.Context, orgID platform.ID, stackIDs []platform.ID) ([]Stack, error) { var stacks []Stack for _, id := range stackIDs { st, err := s.ReadStackByID(ctx, id) - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors.ErrorCode(err) == errors.ENotFound { // since the stackIDs are a filter, if it is not found, we just continue // on. If the user wants to verify the existence of a particular stack // then it would be upon them to use the ReadByID call. @@ -177,7 +179,7 @@ func (s *StoreKV) listStacksByID(ctx context.Context, orgID influxdb.ID, stackID } // ReadStackByID reads a stack by the provided ID. -func (s *StoreKV) ReadStackByID(ctx context.Context, id influxdb.ID) (Stack, error) { +func (s *StoreKV) ReadStackByID(ctx context.Context, id platform.ID) (Stack, error) { var stack Stack err := s.view(ctx, func(tx kv.Tx) error { decodedEnt, err := s.indexBase.FindEnt(ctx, tx, kv.Entity{PK: kv.EncID(id)}) @@ -198,8 +200,8 @@ func (s *StoreKV) UpdateStack(ctx context.Context, stack Stack) error { } if stack.OrgID != existing.OrgID { - return &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + return &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: "org id does not match", } } @@ -208,7 +210,7 @@ func (s *StoreKV) UpdateStack(ctx context.Context, stack Stack) error { } // DeleteStack deletes a stack by id. -func (s *StoreKV) DeleteStack(ctx context.Context, id influxdb.ID) error { +func (s *StoreKV) DeleteStack(ctx context.Context, id platform.ID) error { return s.kvStore.Update(ctx, func(tx kv.Tx) error { return s.indexBase.DeleteEnt(ctx, tx, kv.Entity{PK: kv.EncID(id)}) }) @@ -217,7 +219,7 @@ func (s *StoreKV) DeleteStack(ctx context.Context, id influxdb.ID) error { func (s *StoreKV) put(ctx context.Context, stack Stack, opts ...kv.PutOptionFn) error { ent, err := convertStackToEnt(stack) if err != nil { - return influxErr(influxdb.EInvalid, err) + return influxErr(errors.EInvalid, err) } return s.kvStore.Update(ctx, func(tx kv.Tx) error { @@ -251,7 +253,7 @@ func (s *StoreKV) entStoreBase(resource string) *kv.StoreBase { func (s *StoreKV) indexStoreBase(resource string) *kv.StoreBase { var decValToEntFn kv.ConvertValToEntFn = func(k []byte, v interface{}) (kv.Entity, error) { - id, ok := v.(influxdb.ID) + id, ok := v.(platform.ID) if err := kv.IsErrUnexpectedDecodeVal(ok); err != nil { return kv.Entity{}, err } diff --git a/pkger/store_test.go b/pkger/store_test.go index e2220af0295..a3cf0344d69 100644 --- a/pkger/store_test.go +++ b/pkger/store_test.go @@ -2,6 +2,8 @@ package pkger_test import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "testing" "time" @@ -9,7 +11,6 @@ import ( "github.com/influxdata/influxdb/v2/kv/migration/all" "go.uber.org/zap/zaptest" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/pkger" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -23,7 +24,7 @@ func TestStoreKV(t *testing.T) { t.Fatal(err) } - stackStub := func(id, orgID influxdb.ID) pkger.Stack { + stackStub := func(id, orgID platform.ID) pkger.Stack { now := time.Time{}.Add(10 * 365 * 24 * time.Hour) urls := []string{ "http://example.com", @@ -85,13 +86,13 @@ func TestStoreKV(t *testing.T) { }) t.Run("with ID collisions fails with conflict error", func(t *testing.T) { - for _, id := range []influxdb.ID{2, 3} { + for _, id := range []platform.ID{2, 3} { err := storeKV.CreateStack(context.Background(), pkger.Stack{ ID: 1, OrgID: orgID, }) require.Errorf(t, err, "id=%d", id) - assert.Equalf(t, influxdb.EConflict, influxdb.ErrorCode(err), "id=%d", id) + assert.Equalf(t, errors.EConflict, errors.ErrorCode(err), "id=%d", id) } }) }) @@ -136,7 +137,7 @@ func TestStoreKV(t *testing.T) { tests := []struct { name string - orgID influxdb.ID + orgID platform.ID filter pkger.ListFilter expected []pkger.Stack }{ @@ -164,7 +165,7 @@ func TestStoreKV(t *testing.T) { name: "by stack ids", orgID: orgID1, filter: pkger.ListFilter{ - StackIDs: []influxdb.ID{1, 3}, + StackIDs: []platform.ID{1, 3}, }, expected: []pkger.Stack{ { @@ -187,7 +188,7 @@ func TestStoreKV(t *testing.T) { name: "by stack ids skips ids that belong to different organization", orgID: orgID1, filter: pkger.ListFilter{ - StackIDs: []influxdb.ID{1, 2, 4}, + StackIDs: []platform.ID{1, 2, 4}, }, expected: []pkger.Stack{{ ID: 1, @@ -201,7 +202,7 @@ func TestStoreKV(t *testing.T) { name: "stack ids that do not exist are skipped", orgID: orgID1, filter: pkger.ListFilter{ - StackIDs: []influxdb.ID{1, 9000}, + StackIDs: []platform.ID{1, 9000}, }, expected: []pkger.Stack{{ ID: 1, @@ -229,7 +230,7 @@ func TestStoreKV(t *testing.T) { name: "by name and id", orgID: orgID1, filter: pkger.ListFilter{ - StackIDs: []influxdb.ID{3}, + StackIDs: []platform.ID{3}, Names: []string{"first_name"}, }, expected: []pkger.Stack{ @@ -276,10 +277,10 @@ func TestStoreKV(t *testing.T) { }) t.Run("when no match found fails with not found error", func(t *testing.T) { - unmatchedID := influxdb.ID(3000) + unmatchedID := platform.ID(3000) _, err := storeKV.ReadStackByID(context.Background(), unmatchedID) require.Error(t, err) - assert.Equal(t, influxdb.ENotFound, influxdb.ErrorCode(err)) + assert.Equal(t, errors.ENotFound, errors.ErrorCode(err)) }) }) @@ -314,13 +315,13 @@ func TestStoreKV(t *testing.T) { }) t.Run("when no match found fails with not found error", func(t *testing.T) { - unmatchedID := influxdb.ID(3000) + unmatchedID := platform.ID(3000) err := storeKV.UpdateStack(context.Background(), pkger.Stack{ ID: unmatchedID, OrgID: orgID, }) require.Error(t, err) - assert.Equalf(t, influxdb.ENotFound, influxdb.ErrorCode(err), "err: %s", err) + assert.Equalf(t, errors.ENotFound, errors.ErrorCode(err), "err: %s", err) }) t.Run("when org id does not match fails with unprocessable entity error", func(t *testing.T) { @@ -329,7 +330,7 @@ func TestStoreKV(t *testing.T) { OrgID: orgID + 9000, }) require.Error(t, err) - assert.Equalf(t, influxdb.EUnprocessableEntity, influxdb.ErrorCode(err), "err: %s", err) + assert.Equalf(t, errors.EUnprocessableEntity, errors.ErrorCode(err), "err: %s", err) }) }) @@ -349,14 +350,14 @@ func TestStoreKV(t *testing.T) { _, err = storeKV.ReadStackByID(context.Background(), expected.ID) require.Error(t, err) - errCodeEqual(t, influxdb.ENotFound, err) + errCodeEqual(t, errors.ENotFound, err) }) t.Run("when no match found fails with not found error", func(t *testing.T) { - unmatchedID := influxdb.ID(3000) + unmatchedID := platform.ID(3000) err := storeKV.DeleteStack(context.Background(), unmatchedID) require.Error(t, err) - errCodeEqual(t, influxdb.ENotFound, err) + errCodeEqual(t, errors.ENotFound, err) }) }) } @@ -372,7 +373,7 @@ func readStackEqual(t *testing.T, store pkger.Store, expected pkger.Stack) { func errCodeEqual(t *testing.T, expected string, actual error) { t.Helper() - assert.Equalf(t, expected, influxdb.ErrorCode(actual), "err: %s", actual) + assert.Equalf(t, expected, errors.ErrorCode(actual), "err: %s", actual) } func seedEntities(t *testing.T, store pkger.Store, first pkger.Stack, rest ...pkger.Stack) { diff --git a/pprof/http_server.go b/pprof/http_server.go index b7a4175ed97..4c91b7bbb61 100644 --- a/pprof/http_server.go +++ b/pprof/http_server.go @@ -8,8 +8,9 @@ import ( "strconv" "time" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" - "github.com/influxdata/influxdb/v2" ihttp "github.com/influxdata/influxdb/v2/kit/transport/http" ) @@ -36,7 +37,7 @@ func NewHTTPHandler(profilingEnabled bool) *Handler { } func profilingDisabledHandler(w http.ResponseWriter, r *http.Request) { - ihttp.WriteErrorResponse(r.Context(), w, influxdb.EForbidden, "profiling disabled") + ihttp.WriteErrorResponse(r.Context(), w, errors.EForbidden, "profiling disabled") } func archiveProfilesHandler(w http.ResponseWriter, r *http.Request) { @@ -48,7 +49,7 @@ func archiveProfilesHandler(w http.ResponseWriter, r *http.Request) { // distinguish between a form value that exists and has no value and one that // does not exist at all. if err := r.ParseForm(); err != nil { - ihttp.WriteErrorResponse(ctx, w, influxdb.EInternal, err.Error()) + ihttp.WriteErrorResponse(ctx, w, errors.EInternal, err.Error()) return } @@ -95,18 +96,18 @@ func archiveProfilesHandler(w http.ResponseWriter, r *http.Request) { // In this case it is a StatusBadRequest (400) since the problem is in the // supplied form data. if duration < 0 { - ihttp.WriteErrorResponse(ctx, w, influxdb.EInvalid, "negative trace durations not allowed") + ihttp.WriteErrorResponse(ctx, w, errors.EInvalid, "negative trace durations not allowed") return } if err != nil { - ihttp.WriteErrorResponse(ctx, w, influxdb.EInvalid, fmt.Sprintf("could not parse supplied duration for trace %q", val)) + ihttp.WriteErrorResponse(ctx, w, errors.EInvalid, fmt.Sprintf("could not parse supplied duration for trace %q", val)) return } // Trace files can get big. Lets clamp the maximum trace duration to 45s. if duration > 45*time.Second { - ihttp.WriteErrorResponse(ctx, w, influxdb.EInvalid, "cannot trace for longer than 45s") + ihttp.WriteErrorResponse(ctx, w, errors.EInvalid, "cannot trace for longer than 45s") return } @@ -155,7 +156,7 @@ func archiveProfilesHandler(w http.ResponseWriter, r *http.Request) { duration, err := getDuration() if err != nil { - ihttp.WriteErrorResponse(ctx, w, influxdb.EInvalid, fmt.Sprintf("could not parse supplied duration for cpu profile %q", val)) + ihttp.WriteErrorResponse(ctx, w, errors.EInvalid, fmt.Sprintf("could not parse supplied duration for cpu profile %q", val)) return } @@ -164,7 +165,7 @@ func archiveProfilesHandler(w http.ResponseWriter, r *http.Request) { tarstream, err := collectAllProfiles(ctx, traceDuration, cpuDuration) if err != nil { - ihttp.WriteErrorResponse(ctx, w, influxdb.EInternal, err.Error()) + ihttp.WriteErrorResponse(ctx, w, errors.EInternal, err.Error()) return } _, _ = io.Copy(w, tarstream) diff --git a/predicate/logical.go b/predicate/logical.go index 894a8967794..0c526df3ae6 100644 --- a/predicate/logical.go +++ b/predicate/logical.go @@ -3,7 +3,8 @@ package predicate import ( "fmt" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2/storage/reads/datatypes" ) @@ -21,8 +22,8 @@ func (op LogicalOperator) Value() (datatypes.Node_Logical, error) { case LogicalAnd: return datatypes.LogicalAnd, nil default: - return 0, &influxdb.Error{ - Code: influxdb.EInvalid, + return 0, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("the logical operator %q is invalid", op), } } @@ -44,8 +45,8 @@ func (n LogicalNode) ToDataType() (*datatypes.Node, error) { for k, node := range n.Children { children[k], err = node.ToDataType() if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("Err in Child %d, err: %s", k, err.Error()), } } diff --git a/predicate/parser.go b/predicate/parser.go index 3027e1b26bc..d05ab3f4eaf 100644 --- a/predicate/parser.go +++ b/predicate/parser.go @@ -4,6 +4,8 @@ import ( "fmt" "strings" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxql" ) @@ -108,8 +110,8 @@ func (p *parser) parseLogicalNode() (Node, error) { Operator: LogicalAnd, } case influxql.OR: - return *n, &influxdb.Error{ - Code: influxdb.EInvalid, + return *n, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("the logical operator OR is not supported yet at position %d", pos.Char), } case influxql.LPAREN: @@ -120,8 +122,8 @@ func (p *parser) parseLogicalNode() (Node, error) { return *n, err } if p.openParen != currParen-1 { - return *n, &influxdb.Error{ - Code: influxdb.EInvalid, + return *n, &errors.Error{ + Code: errors.EInvalid, Msg: "extra ( seen", } } @@ -135,8 +137,8 @@ func (p *parser) parseLogicalNode() (Node, error) { fallthrough case influxql.EOF: if p.openParen < 0 { - return *n, &influxdb.Error{ - Code: influxdb.EInvalid, + return *n, &errors.Error{ + Code: errors.EInvalid, Msg: "extra ) seen", } } @@ -145,8 +147,8 @@ func (p *parser) parseLogicalNode() (Node, error) { } return *n, nil default: - return *n, &influxdb.Error{ - Code: influxdb.EInvalid, + return *n, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("bad logical expression, at position %d", pos.Char), } } @@ -163,8 +165,8 @@ func (p *parser) parseTagRuleNode() (TagRuleNode, error) { case influxql.NAME: n.Key = "name" default: - return *n, &influxdb.Error{ - Code: influxdb.EInvalid, + return *n, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("bad tag key, at position %d", pos.Char), } } @@ -180,13 +182,13 @@ func (p *parser) parseTagRuleNode() (TagRuleNode, error) { case influxql.EQREGEX: fallthrough case influxql.NEQREGEX: - return *n, &influxdb.Error{ - Code: influxdb.EInvalid, + return *n, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("operator: %q at position: %d is not supported yet", tok.String(), pos.Char), } default: - return *n, &influxdb.Error{ - Code: influxdb.EInvalid, + return *n, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("invalid operator %q at position: %d", tok.String(), pos.Char), } } @@ -213,8 +215,8 @@ scanRegularTagValue: n.Value = "false" return *n, nil default: - return *n, &influxdb.Error{ - Code: influxdb.EInvalid, + return *n, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("bad tag value: %q, at position %d", lit, pos.Char), } } diff --git a/predicate/parser_test.go b/predicate/parser_test.go index 411d4554fe0..5577170469c 100644 --- a/predicate/parser_test.go +++ b/predicate/parser_test.go @@ -4,6 +4,8 @@ import ( "strings" "testing" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" influxtesting "github.com/influxdata/influxdb/v2/testing" @@ -39,8 +41,8 @@ func TestParseNode(t *testing.T) { }, { str: ` abc="opq" Or gender="male" OR temp=1123`, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "the logical operator OR is not supported yet at position 11", }, }, @@ -65,15 +67,15 @@ func TestParseNode(t *testing.T) { }, { str: ` (t1="v1" and t2="v2") and (`, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "extra ( seen", }, }, { str: ` (t1="v1" and t2="v2"))`, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "extra ) seen", }, }, @@ -133,22 +135,22 @@ func TestParseTagRule(t *testing.T) { }, { str: `abc!~/^payments\./`, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: `operator: "!~" at position: 3 is not supported yet`, }, }, { str: `abc=~/^payments\./`, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: `operator: "=~" at position: 3 is not supported yet`, }, }, { str: `abc>1000`, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: `invalid operator ">" at position: 3`, }, }, diff --git a/predicate/predicate.go b/predicate/predicate.go index ffed5161a56..a0ef42e1080 100644 --- a/predicate/predicate.go +++ b/predicate/predicate.go @@ -2,6 +2,7 @@ package predicate import ( "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "github.com/influxdata/influxdb/v2/storage/reads/datatypes" "github.com/influxdata/influxdb/v2/tsdb/engine/tsm1" ) @@ -25,8 +26,8 @@ func New(n Node) (influxdb.Predicate, error) { Root: dt, }) if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } diff --git a/predicate/tag_rule.go b/predicate/tag_rule.go index 503e9676aae..42e06959f92 100644 --- a/predicate/tag_rule.go +++ b/predicate/tag_rule.go @@ -3,6 +3,8 @@ package predicate import ( "fmt" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/models" "github.com/influxdata/influxdb/v2/storage/reads/datatypes" @@ -48,13 +50,13 @@ func NodeComparison(op influxdb.Operator) (datatypes.Node_Comparison, error) { case influxdb.RegexEqual: fallthrough case influxdb.NotRegexEqual: - return 0, &influxdb.Error{ - Code: influxdb.EInvalid, + return 0, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("Operator %s is not supported for delete predicate yet", op), } default: - return 0, &influxdb.Error{ - Code: influxdb.EInvalid, + return 0, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("Unsupported operator: %s", op), } } diff --git a/prometheus/auth_service.go b/prometheus/auth_service.go index 1cf15ed9105..d056b408b1c 100644 --- a/prometheus/auth_service.go +++ b/prometheus/auth_service.go @@ -5,6 +5,8 @@ import ( "fmt" "time" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" "github.com/prometheus/client_golang/prometheus" ) @@ -42,7 +44,7 @@ func NewAuthorizationService() *AuthorizationService { } // FindAuthorizationByID returns an authorization given a id, records function call latency, and counts function calls. -func (s *AuthorizationService) FindAuthorizationByID(ctx context.Context, id platform.ID) (a *platform.Authorization, err error) { +func (s *AuthorizationService) FindAuthorizationByID(ctx context.Context, id platform2.ID) (a *platform.Authorization, err error) { defer func(start time.Time) { labels := prometheus.Labels{ "method": "FindAuthorizationByID", @@ -96,7 +98,7 @@ func (s *AuthorizationService) CreateAuthorization(ctx context.Context, a *platf } // DeleteAuthorization deletes an authorization, records function call latency, and counts function calls. -func (s *AuthorizationService) DeleteAuthorization(ctx context.Context, id platform.ID) (err error) { +func (s *AuthorizationService) DeleteAuthorization(ctx context.Context, id platform2.ID) (err error) { defer func(start time.Time) { labels := prometheus.Labels{ "method": "DeleteAuthorization", @@ -110,7 +112,7 @@ func (s *AuthorizationService) DeleteAuthorization(ctx context.Context, id platf } // UpdateAuthorization updates the status and description. -func (s *AuthorizationService) UpdateAuthorization(ctx context.Context, id platform.ID, upd *platform.AuthorizationUpdate) (a *platform.Authorization, err error) { +func (s *AuthorizationService) UpdateAuthorization(ctx context.Context, id platform2.ID, upd *platform.AuthorizationUpdate) (a *platform.Authorization, err error) { defer func(start time.Time) { labels := prometheus.Labels{ "method": "setAuthorizationStatus", diff --git a/prometheus/auth_service_test.go b/prometheus/auth_service_test.go index 9ab568f8ed3..f3a522dff90 100644 --- a/prometheus/auth_service_test.go +++ b/prometheus/auth_service_test.go @@ -3,6 +3,7 @@ package prometheus_test import ( "context" "errors" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" "testing" platform "github.com/influxdata/influxdb/v2" @@ -19,7 +20,7 @@ type authzSvc struct { var _ platform.AuthorizationService = (*authzSvc)(nil) -func (a *authzSvc) FindAuthorizationByID(context.Context, platform.ID) (*platform.Authorization, error) { +func (a *authzSvc) FindAuthorizationByID(context.Context, platform2.ID) (*platform.Authorization, error) { return nil, a.Err } @@ -35,11 +36,11 @@ func (a *authzSvc) CreateAuthorization(context.Context, *platform.Authorization) return a.Err } -func (a *authzSvc) DeleteAuthorization(context.Context, platform.ID) error { +func (a *authzSvc) DeleteAuthorization(context.Context, platform2.ID) error { return a.Err } -func (a *authzSvc) UpdateAuthorization(context.Context, platform.ID, *platform.AuthorizationUpdate) (*platform.Authorization, error) { +func (a *authzSvc) UpdateAuthorization(context.Context, platform2.ID, *platform.AuthorizationUpdate) (*platform.Authorization, error) { return nil, a.Err } @@ -52,7 +53,7 @@ func TestAuthorizationService_Metrics(t *testing.T) { reg.MustRegister(svc.PrometheusCollectors()...) ctx := context.Background() - id := platform.ID(1) + id := platform2.ID(1) if _, err := svc.FindAuthorizationByID(ctx, id); err != nil { t.Fatal(err) @@ -90,7 +91,7 @@ func TestAuthorizationService_Metrics(t *testing.T) { t.Fatalf("exp 1 request, got %v", got) } - var tempID platform.ID + var tempID platform2.ID if err := svc.DeleteAuthorization(ctx, tempID); err != nil { t.Fatal(err) } diff --git a/prometheus/influx.go b/prometheus/influx.go index 64fcb185a81..79bfc8713e6 100644 --- a/prometheus/influx.go +++ b/prometheus/influx.go @@ -5,6 +5,8 @@ import ( "strconv" "time" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" "github.com/prometheus/client_golang/prometheus" ) @@ -16,7 +18,7 @@ type influxCollector struct { } // NewInfluxCollector returns a collector which exports influxdb process metrics. -func NewInfluxCollector(procID platform.IDGenerator, build platform.BuildInfo) prometheus.Collector { +func NewInfluxCollector(procID platform2.IDGenerator, build platform.BuildInfo) prometheus.Collector { id := procID.ID().String() return &influxCollector{ diff --git a/query/bridges.go b/query/bridges.go index 564f5546fca..f0ce6c093b5 100644 --- a/query/bridges.go +++ b/query/bridges.go @@ -5,6 +5,8 @@ import ( "context" "io" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/flux" "github.com/influxdata/flux/csv" platform "github.com/influxdata/influxdb/v2" @@ -172,7 +174,7 @@ type REPLQuerier struct { // Authorization is the authorization to provide for all requests Authorization *platform.Authorization // OrganizationID is the ID to provide for all requests - OrganizationID platform.ID + OrganizationID platform2.ID QueryService QueryService } diff --git a/query/control/controller.go b/query/control/controller.go index 552dbf46d8f..ba0c3d7ce80 100644 --- a/query/control/controller.go +++ b/query/control/controller.go @@ -24,13 +24,14 @@ import ( "sync" "sync/atomic" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/flux" "github.com/influxdata/flux/codes" "github.com/influxdata/flux/execute/table" "github.com/influxdata/flux/lang" "github.com/influxdata/flux/memory" "github.com/influxdata/flux/runtime" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/errors" "github.com/influxdata/influxdb/v2/kit/feature" "github.com/influxdata/influxdb/v2/kit/prom" @@ -1028,7 +1029,7 @@ func handleFluxError(err error) error { } werr := handleFluxError(ferr.Err) - code := influxdb.EInternal + code := errors2.EInternal switch ferr.Code { case codes.Inherit: // If we are inheriting the error code, influxdb doesn't @@ -1036,12 +1037,12 @@ func handleFluxError(err error) error { // the error code from the wrapped error which has already // been translated to an influxdb error (if possible). if werr != nil { - code = influxdb.ErrorCode(werr) + code = errors2.ErrorCode(werr) } case codes.NotFound: - code = influxdb.ENotFound + code = errors2.ENotFound case codes.Invalid: - code = influxdb.EInvalid + code = errors2.EInvalid // These don't really map correctly, but we want // them to show up as 4XX so until influxdb error // codes are updated for more types of failures, @@ -1052,16 +1053,16 @@ func handleFluxError(err error) error { codes.Aborted, codes.OutOfRange, codes.Unimplemented: - code = influxdb.EInvalid + code = errors2.EInvalid case codes.PermissionDenied: - code = influxdb.EForbidden + code = errors2.EForbidden case codes.Unauthenticated: - code = influxdb.EUnauthorized + code = errors2.EUnauthorized default: // Everything else is treated as an internal error // which is set above. } - return &influxdb.Error{ + return &errors2.Error{ Code: code, Msg: ferr.Msg, Err: werr, diff --git a/query/dependency.go b/query/dependency.go index 2cec2f95495..0ef9ebe1f27 100644 --- a/query/dependency.go +++ b/query/dependency.go @@ -3,6 +3,8 @@ package query import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/flux" "github.com/influxdata/flux/codes" "github.com/influxdata/influxdb/v2" @@ -21,20 +23,20 @@ type BucketLookup struct { } // Lookup returns the bucket id and its existence given an org id and bucket name. -func (b *BucketLookup) Lookup(ctx context.Context, orgID influxdb.ID, name string) (influxdb.ID, bool) { +func (b *BucketLookup) Lookup(ctx context.Context, orgID platform.ID, name string) (platform.ID, bool) { filter := influxdb.BucketFilter{ OrganizationID: &orgID, Name: &name, } bucket, err := b.BucketService.FindBucket(ctx, filter) if err != nil { - return influxdb.InvalidID(), false + return platform.InvalidID(), false } return bucket.ID, true } // LookupName returns an bucket name given its organization ID and its bucket ID. -func (b *BucketLookup) LookupName(ctx context.Context, orgID influxdb.ID, id influxdb.ID) string { +func (b *BucketLookup) LookupName(ctx context.Context, orgID platform.ID, id platform.ID) string { filter := influxdb.BucketFilter{ OrganizationID: &orgID, ID: &id, @@ -46,7 +48,7 @@ func (b *BucketLookup) LookupName(ctx context.Context, orgID influxdb.ID, id inf return bucket.Name } -func (b *BucketLookup) FindAllBuckets(ctx context.Context, orgID influxdb.ID) ([]*influxdb.Bucket, int) { +func (b *BucketLookup) FindAllBuckets(ctx context.Context, orgID platform.ID) ([]*influxdb.Bucket, int) { filter := influxdb.BucketFilter{ OrganizationID: &orgID, } @@ -77,21 +79,21 @@ type OrganizationLookup struct { } // Lookup returns the organization ID and its existence given an organization name. -func (o *OrganizationLookup) Lookup(ctx context.Context, name string) (influxdb.ID, bool) { +func (o *OrganizationLookup) Lookup(ctx context.Context, name string) (platform.ID, bool) { org, err := o.OrganizationService.FindOrganization( ctx, influxdb.OrganizationFilter{Name: &name}, ) if err != nil { - return influxdb.InvalidID(), false + return platform.InvalidID(), false } return org.ID, true } // LookupName returns an organization name given its ID. -func (o *OrganizationLookup) LookupName(ctx context.Context, id influxdb.ID) string { - id = influxdb.ID(id) +func (o *OrganizationLookup) LookupName(ctx context.Context, id platform.ID) string { + id = platform.ID(id) org, err := o.OrganizationService.FindOrganization( ctx, influxdb.OrganizationFilter{ diff --git a/query/dependency_test.go b/query/dependency_test.go index 05d454f0107..ad761a3e0db 100644 --- a/query/dependency_test.go +++ b/query/dependency_test.go @@ -2,9 +2,9 @@ package query_test import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" "testing" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" "github.com/influxdata/influxdb/v2/query" ) @@ -13,7 +13,7 @@ func TestSecretLookup(t *testing.T) { req := &query.Request{OrganizationID: orgID} ctx := query.ContextWithRequest(context.Background(), req) svc := &mock.SecretService{ - LoadSecretFn: func(ctx context.Context, orgID influxdb.ID, k string) (string, error) { + LoadSecretFn: func(ctx context.Context, orgID platform.ID, k string) (string, error) { if want, got := req.OrganizationID, orgID; want != got { t.Errorf("unexpected organization id -want/+got:\n\t- %v\n\t+ %v", want, got) } diff --git a/query/influxql/end_to_end_test.go b/query/influxql/end_to_end_test.go index 02c6ab633e3..3d20b1d1d8e 100644 --- a/query/influxql/end_to_end_test.go +++ b/query/influxql/end_to_end_test.go @@ -4,6 +4,7 @@ import ( "bufio" "bytes" "context" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" "io" "io/ioutil" "os" @@ -17,9 +18,9 @@ import ( "github.com/influxdata/flux/memory" fluxquerytest "github.com/influxdata/flux/querytest" platform "github.com/influxdata/influxdb/v2" + _ "github.com/influxdata/influxdb/v2/fluxinit/static" "github.com/influxdata/influxdb/v2/mock" "github.com/influxdata/influxdb/v2/query" - _ "github.com/influxdata/influxdb/v2/fluxinit/static" "github.com/influxdata/influxdb/v2/query/influxql" "github.com/influxdata/influxdb/v2/query/querytest" platformtesting "github.com/influxdata/influxdb/v2/testing" @@ -37,7 +38,7 @@ func init() { OrganizationID: platformtesting.MustIDBase16("cadecadecadecade"), BucketID: platformtesting.MustIDBase16("da7aba5e5eedca5e"), } - dbrpMappingSvcE2E.FindByIDFn = func(ctx context.Context, orgID, id platform.ID) (*platform.DBRPMappingV2, error) { + dbrpMappingSvcE2E.FindByIDFn = func(ctx context.Context, orgID, id platform2.ID) (*platform.DBRPMappingV2, error) { return &mapping, nil } dbrpMappingSvcE2E.FindManyFn = func(ctx context.Context, filter platform.DBRPMappingFilterV2, opt ...platform.FindOptions) ([]*platform.DBRPMappingV2, int, error) { diff --git a/query/influxql/spectests/testing.go b/query/influxql/spectests/testing.go index 23b50ef7096..deca31134cd 100644 --- a/query/influxql/spectests/testing.go +++ b/query/influxql/spectests/testing.go @@ -7,6 +7,8 @@ import ( "testing" "time" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/andreyvit/diff" "github.com/influxdata/flux/ast" "github.com/influxdata/flux/parser" @@ -17,9 +19,9 @@ import ( ) var dbrpMappingSvc = &mock.DBRPMappingServiceV2{} -var organizationID platform.ID -var bucketID platform.ID -var altBucketID platform.ID +var organizationID platform2.ID +var bucketID platform2.ID +var altBucketID platform2.ID func init() { mapping := platform.DBRPMappingV2{ @@ -36,7 +38,7 @@ func init() { OrganizationID: organizationID, BucketID: altBucketID, } - dbrpMappingSvc.FindByIDFn = func(ctx context.Context, orgID, id platform.ID) (*platform.DBRPMappingV2, error) { + dbrpMappingSvc.FindByIDFn = func(ctx context.Context, orgID, id platform2.ID) (*platform.DBRPMappingV2, error) { return &mapping, nil } dbrpMappingSvc.FindManyFn = func(ctx context.Context, filter platform.DBRPMappingFilterV2, opt ...platform.FindOptions) ([]*platform.DBRPMappingV2, int, error) { diff --git a/query/influxql/transpiler.go b/query/influxql/transpiler.go index 0a3a25c13e1..ce6458a2c7e 100644 --- a/query/influxql/transpiler.go +++ b/query/influxql/transpiler.go @@ -8,6 +8,8 @@ import ( "strconv" "time" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/flux/ast" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxql" @@ -622,8 +624,8 @@ func (t *transpilerState) transpileSelect(ctx context.Context, stmt *influxql.Se if err != nil { return nil, err } else if len(groups) == 0 { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unable to transpile: at least one non-time field must be queried", } } @@ -674,16 +676,16 @@ func (t *transpilerState) from(m *influxql.Measurement) (ast.Expression, error) } } else { if t.dbrpMappingSvc == nil { - return nil, &influxdb.Error{ - Code: influxdb.EInternal, + return nil, &errors.Error{ + Code: errors.EInternal, Msg: "unable to transpile: db and rp mappings need to be created by some way", } } db, rp := m.Database, m.RetentionPolicy if db == "" { if t.config.DefaultDatabase == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unable to transpile: database is required", } } diff --git a/query/influxql/transpiler_test.go b/query/influxql/transpiler_test.go index 6151ad2aba5..32398385a26 100644 --- a/query/influxql/transpiler_test.go +++ b/query/influxql/transpiler_test.go @@ -2,6 +2,7 @@ package influxql_test import ( "context" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" "strings" "testing" @@ -23,7 +24,7 @@ func init() { OrganizationID: platformtesting.MustIDBase16("aaaaaaaaaaaaaaaa"), BucketID: platformtesting.MustIDBase16("bbbbbbbbbbbbbbbb"), } - dbrpMappingSvc.FindByIDFn = func(ctx context.Context, orgID, id platform.ID) (*platform.DBRPMappingV2, error) { + dbrpMappingSvc.FindByIDFn = func(ctx context.Context, orgID, id platform2.ID) (*platform.DBRPMappingV2, error) { return &mapping, nil } dbrpMappingSvc.FindManyFn = func(ctx context.Context, filter platform.DBRPMappingFilterV2, opt ...platform.FindOptions) ([]*platform.DBRPMappingV2, int, error) { diff --git a/query/logger.go b/query/logger.go index dd54c8dfba3..a2f13785cf1 100644 --- a/query/logger.go +++ b/query/logger.go @@ -3,6 +3,8 @@ package query import ( "time" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/flux" platform "github.com/influxdata/influxdb/v2" ) @@ -17,7 +19,7 @@ type Log struct { // Time is the time the query was completed Time time.Time // OrganizationID is the ID of the organization that requested the query - OrganizationID platform.ID + OrganizationID platform2.ID // TraceID is the ID of the trace related to this query TraceID string // Sampled specifies whether the trace for TraceID was chosen for permanent storage diff --git a/query/logging_test.go b/query/logging_test.go index 823660f2ff3..809f9c30d6e 100644 --- a/query/logging_test.go +++ b/query/logging_test.go @@ -3,6 +3,7 @@ package query_test import ( "bytes" "context" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" "io" "io/ioutil" "testing" @@ -12,7 +13,6 @@ import ( "github.com/google/go-cmp/cmp/cmpopts" "github.com/influxdata/flux" "github.com/influxdata/flux/metadata" - platform "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/query" "github.com/influxdata/influxdb/v2/query/mock" "github.com/opentracing/opentracing-go" @@ -23,8 +23,8 @@ import ( var orgID = MustIDBase16("ba55ba55ba55ba55") // MustIDBase16 is an helper to ensure a correct ID is built during testing. -func MustIDBase16(s string) platform.ID { - id, err := platform.IDFromString(s) +func MustIDBase16(s string) platform2.ID { + id, err := platform2.IDFromString(s) if err != nil { panic(err) } diff --git a/query/request.go b/query/request.go index 6eec3b3bbf7..30dad9602b7 100644 --- a/query/request.go +++ b/query/request.go @@ -6,6 +6,8 @@ import ( "fmt" "net/http" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/flux" platform "github.com/influxdata/influxdb/v2" ) @@ -23,7 +25,7 @@ const ( type Request struct { // Scope Authorization *platform.Authorization `json:"authorization,omitempty"` - OrganizationID platform.ID `json:"organization_id"` + OrganizationID platform2.ID `json:"organization_id"` // Command diff --git a/query/service.go b/query/service.go index 67ce538bb8a..950a5fbada1 100644 --- a/query/service.go +++ b/query/service.go @@ -4,6 +4,8 @@ import ( "context" "io" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/flux" "github.com/influxdata/flux/ast" "github.com/influxdata/flux/interpreter" @@ -46,8 +48,8 @@ type ProxyQueryService interface { // This will return an error if the FluxLanguageService is nil. func Parse(lang influxdb.FluxLanguageService, source string) (*ast.Package, error) { if lang == nil { - return nil, &influxdb.Error{ - Code: influxdb.EInternal, + return nil, &errors.Error{ + Code: errors.EInternal, Msg: "flux is not configured; cannot parse", } } @@ -59,8 +61,8 @@ func Parse(lang influxdb.FluxLanguageService, source string) (*ast.Package, erro // This will return an error if the FluxLanguageService is nil. func EvalAST(ctx context.Context, lang influxdb.FluxLanguageService, astPkg *ast.Package) ([]interpreter.SideEffect, values.Scope, error) { if lang == nil { - return nil, nil, &influxdb.Error{ - Code: influxdb.EInternal, + return nil, nil, &errors.Error{ + Code: errors.EInternal, Msg: "flux is not configured; cannot evaluate", } } diff --git a/query/stdlib/experimental/to.go b/query/stdlib/experimental/to.go index e3d2b06c1aa..b5cf932fada 100644 --- a/query/stdlib/experimental/to.go +++ b/query/stdlib/experimental/to.go @@ -5,6 +5,8 @@ import ( "errors" "fmt" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/flux" "github.com/influxdata/flux/codes" "github.com/influxdata/flux/execute" @@ -94,13 +96,13 @@ func (ToOpSpec) Kind() flux.OperationKind { } // BucketsAccessed returns the buckets accessed by the spec. -func (o *ToOpSpec) BucketsAccessed(orgID *platform.ID) (readBuckets, writeBuckets []platform.BucketFilter) { +func (o *ToOpSpec) BucketsAccessed(orgID *platform2.ID) (readBuckets, writeBuckets []platform.BucketFilter) { bf := platform.BucketFilter{} if o.Bucket != "" { bf.Name = &o.Bucket } if o.BucketID != "" { - id, err := platform.IDFromString(o.BucketID) + id, err := platform2.IDFromString(o.BucketID) if err == nil { bf.ID = id } @@ -109,7 +111,7 @@ func (o *ToOpSpec) BucketsAccessed(orgID *platform.ID) (readBuckets, writeBucket bf.Org = &o.Org } if o.OrgID != "" { - id, err := platform.IDFromString(o.OrgID) + id, err := platform2.IDFromString(o.OrgID) if err == nil { bf.OrganizationID = id } @@ -176,8 +178,8 @@ func createToTransformation(id execute.DatasetID, mode execute.AccumulationMode, type ToTransformation struct { execute.ExecutionNode ctx context.Context - bucketID platform.ID - orgID platform.ID + bucketID platform2.ID + orgID platform2.ID d execute.Dataset cache execute.TableBuilderCache spec *ToOpSpec @@ -194,7 +196,7 @@ func (t *ToTransformation) RetractTable(id execute.DatasetID, key flux.GroupKey) func NewToTransformation(ctx context.Context, d execute.Dataset, cache execute.TableBuilderCache, spec *ToProcedureSpec, deps influxdb.ToDependencies) (*ToTransformation, error) { var err error - var orgID platform.ID + var orgID platform2.ID // Get organization name and ID if spec.Spec.Org != "" { oID, ok := deps.OrganizationLookup.Lookup(ctx, spec.Spec.Org) @@ -203,7 +205,7 @@ func NewToTransformation(ctx context.Context, d execute.Dataset, cache execute.T } orgID = oID } else if spec.Spec.OrgID != "" { - if oid, err := platform.IDFromString(spec.Spec.OrgID); err != nil { + if oid, err := platform2.IDFromString(spec.Spec.OrgID); err != nil { return nil, err } else { orgID = *oid @@ -217,7 +219,7 @@ func NewToTransformation(ctx context.Context, d execute.Dataset, cache execute.T orgID = req.OrganizationID } - var bucketID *platform.ID + var bucketID *platform2.ID // Get bucket name and ID // User will have specified exactly one in the ToOpSpec. if spec.Spec.Bucket != "" { @@ -227,7 +229,7 @@ func NewToTransformation(ctx context.Context, d execute.Dataset, cache execute.T } bucketID = &bID } else { - if bucketID, err = platform.IDFromString(spec.Spec.BucketID); err != nil { + if bucketID, err = platform2.IDFromString(spec.Spec.BucketID); err != nil { return nil, err } } diff --git a/query/stdlib/experimental/to_test.go b/query/stdlib/experimental/to_test.go index 1230282d5d2..f51a6343db6 100644 --- a/query/stdlib/experimental/to_test.go +++ b/query/stdlib/experimental/to_test.go @@ -3,6 +3,7 @@ package experimental_test import ( "context" "errors" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" "testing" "time" @@ -12,10 +13,9 @@ import ( "github.com/influxdata/flux/execute/executetest" "github.com/influxdata/flux/querytest" "github.com/influxdata/flux/stdlib/universe" - platform "github.com/influxdata/influxdb/v2" + _ "github.com/influxdata/influxdb/v2/fluxinit/static" "github.com/influxdata/influxdb/v2/mock" "github.com/influxdata/influxdb/v2/models" - _ "github.com/influxdata/influxdb/v2/fluxinit/static" "github.com/influxdata/influxdb/v2/query/stdlib/experimental" "github.com/influxdata/influxdb/v2/query/stdlib/influxdata/influxdb" ) @@ -526,7 +526,7 @@ func mockDependencies() influxdb.ToDependencies { } } -func mockPoints(org, bucket platform.ID, pointdata string) []models.Point { +func mockPoints(org, bucket platform2.ID, pointdata string) []models.Point { points, err := models.ParsePoints([]byte(pointdata)) if err != nil { return nil diff --git a/query/stdlib/influxdata/influxdb/buckets.go b/query/stdlib/influxdata/influxdb/buckets.go index a5de0e7623b..b40b31f35eb 100644 --- a/query/stdlib/influxdata/influxdb/buckets.go +++ b/query/stdlib/influxdata/influxdb/buckets.go @@ -4,6 +4,8 @@ import ( "context" "fmt" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/flux" "github.com/influxdata/flux/codes" "github.com/influxdata/flux/execute" @@ -35,7 +37,7 @@ func (s *LocalBucketsProcedureSpec) Copy() plan.ProcedureSpec { } type BucketsDecoder struct { - orgID platform.ID + orgID platform2.ID deps BucketDependencies buckets []*platform.Bucket alloc *memory.Allocator @@ -140,7 +142,7 @@ func createBucketsSource(prSpec plan.ProcedureSpec, dsid execute.DatasetID, a ex } type AllBucketLookup interface { - FindAllBuckets(ctx context.Context, orgID platform.ID) ([]*platform.Bucket, int) + FindAllBuckets(ctx context.Context, orgID platform2.ID) ([]*platform.Bucket, int) } type BucketDependencies AllBucketLookup diff --git a/query/stdlib/influxdata/influxdb/metrics.go b/query/stdlib/influxdata/influxdb/metrics.go index 1673fbce324..9cbb230e182 100644 --- a/query/stdlib/influxdata/influxdb/metrics.go +++ b/query/stdlib/influxdata/influxdb/metrics.go @@ -5,7 +5,8 @@ import ( "fmt" "time" - platform "github.com/influxdata/influxdb/v2" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/prometheus/client_golang/prometheus" ) @@ -54,7 +55,7 @@ func (m *metrics) PrometheusCollectors() []prometheus.Collector { } } -func (m *metrics) getLabelValues(ctx context.Context, orgID platform.ID, op string) []string { +func (m *metrics) getLabelValues(ctx context.Context, orgID platform2.ID, op string) []string { if m == nil { return nil } diff --git a/query/stdlib/influxdata/influxdb/operators.go b/query/stdlib/influxdata/influxdb/operators.go index e5ad1a00bf9..22e7b72b6a4 100644 --- a/query/stdlib/influxdata/influxdb/operators.go +++ b/query/stdlib/influxdata/influxdb/operators.go @@ -4,11 +4,12 @@ import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/flux" "github.com/influxdata/flux/codes" "github.com/influxdata/flux/plan" "github.com/influxdata/flux/values" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/storage/reads/datatypes" ) @@ -71,7 +72,7 @@ func (s *ReadRangePhysSpec) Copy() plan.ProcedureSpec { return &ns } -func (s *ReadRangePhysSpec) LookupBucketID(ctx context.Context, orgID influxdb.ID, buckets BucketLookup) (influxdb.ID, error) { +func (s *ReadRangePhysSpec) LookupBucketID(ctx context.Context, orgID platform.ID, buckets BucketLookup) (platform.ID, error) { // Determine bucketID switch { case s.Bucket != "": @@ -84,7 +85,7 @@ func (s *ReadRangePhysSpec) LookupBucketID(ctx context.Context, orgID influxdb.I } return b, nil case len(s.BucketID) != 0: - var b influxdb.ID + var b platform.ID if err := b.DecodeFromString(s.BucketID); err != nil { return 0, &flux.Error{ Code: codes.Invalid, diff --git a/query/stdlib/influxdata/influxdb/source.go b/query/stdlib/influxdata/influxdb/source.go index 7214a40cba6..8d2f29df433 100644 --- a/query/stdlib/influxdata/influxdb/source.go +++ b/query/stdlib/influxdata/influxdb/source.go @@ -5,13 +5,14 @@ import ( "errors" "time" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/flux" "github.com/influxdata/flux/codes" "github.com/influxdata/flux/execute" "github.com/influxdata/flux/memory" "github.com/influxdata/flux/metadata" "github.com/influxdata/flux/plan" - platform "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/tracing" "github.com/influxdata/influxdb/v2/query" "github.com/influxdata/influxdb/v2/tsdb/cursors" @@ -40,7 +41,7 @@ type Source struct { runner runner m *metrics - orgID platform.ID + orgID platform2.ID op string } diff --git a/query/stdlib/influxdata/influxdb/source_test.go b/query/stdlib/influxdata/influxdb/source_test.go index 2f599ffcef0..6160e7c13fe 100644 --- a/query/stdlib/influxdata/influxdb/source_test.go +++ b/query/stdlib/influxdata/influxdb/source_test.go @@ -2,6 +2,7 @@ package influxdb_test import ( "context" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" "testing" "time" @@ -13,7 +14,6 @@ import ( "github.com/influxdata/flux/memory" "github.com/influxdata/flux/plan" "github.com/influxdata/flux/stdlib/universe" - platform "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/prom/promtest" "github.com/influxdata/influxdb/v2/mock" "github.com/influxdata/influxdb/v2/query" @@ -98,7 +98,7 @@ const ( func TestMetrics(t *testing.T) { reg := prometheus.NewRegistry() - orgID, err := platform.IDFromString("deadbeefbeefdead") + orgID, err := platform2.IDFromString("deadbeefbeefdead") if err != nil { t.Fatal(err) } @@ -164,7 +164,7 @@ func (t *TableIterator) Statistics() cursors.CursorStats { func TestReadWindowAggregateSource(t *testing.T) { t.Skip("test panics in CI; issue: https://github.com/influxdata/influxdb/issues/17847") - orgID, bucketID := platform.ID(1), platform.ID(2) + orgID, bucketID := platform2.ID(1), platform2.ID(2) executetest.RunSourceHelper(t, []*executetest.Table{ { diff --git a/query/stdlib/influxdata/influxdb/storage.go b/query/stdlib/influxdata/influxdb/storage.go index 07d59ec580d..d1595cbaf8a 100644 --- a/query/stdlib/influxdata/influxdb/storage.go +++ b/query/stdlib/influxdata/influxdb/storage.go @@ -3,7 +3,8 @@ package influxdb import ( "context" - platform "github.com/influxdata/influxdb/v2" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/prom" "github.com/influxdata/influxdb/v2/query" "github.com/pkg/errors" @@ -16,11 +17,11 @@ type HostLookup interface { } type BucketLookup interface { - Lookup(ctx context.Context, orgID platform.ID, name string) (platform.ID, bool) + Lookup(ctx context.Context, orgID platform2.ID, name string) (platform2.ID, bool) } type OrganizationLookup interface { - Lookup(ctx context.Context, name string) (platform.ID, bool) + Lookup(ctx context.Context, name string) (platform2.ID, bool) } type FromDependencies struct { diff --git a/query/stdlib/influxdata/influxdb/to.go b/query/stdlib/influxdata/influxdb/to.go index b57adf2c5cc..22b21b7afa9 100644 --- a/query/stdlib/influxdata/influxdb/to.go +++ b/query/stdlib/influxdata/influxdb/to.go @@ -6,6 +6,9 @@ import ( "sort" "time" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/flux" "github.com/influxdata/flux/codes" "github.com/influxdata/flux/compiler" @@ -164,13 +167,13 @@ func (ToOpSpec) Kind() flux.OperationKind { } // BucketsAccessed returns the buckets accessed by the spec. -func (o *ToOpSpec) BucketsAccessed(orgID *platform.ID) (readBuckets, writeBuckets []platform.BucketFilter) { +func (o *ToOpSpec) BucketsAccessed(orgID *platform2.ID) (readBuckets, writeBuckets []platform.BucketFilter) { bf := platform.BucketFilter{} if o.Bucket != "" { bf.Name = &o.Bucket } if o.BucketID != "" { - id, err := platform.IDFromString(o.BucketID) + id, err := platform2.IDFromString(o.BucketID) if err == nil { bf.ID = id } @@ -179,7 +182,7 @@ func (o *ToOpSpec) BucketsAccessed(orgID *platform.ID) (readBuckets, writeBucket bf.Org = &o.Org } if o.OrgID != "" { - id, err := platform.IDFromString(o.OrgID) + id, err := platform2.IDFromString(o.OrgID) if err == nil { bf.OrganizationID = id } @@ -259,8 +262,8 @@ func createToTransformation(id execute.DatasetID, mode execute.AccumulationMode, type ToTransformation struct { execute.ExecutionNode Ctx context.Context - OrgID platform.ID - BucketID platform.ID + OrgID platform2.ID + BucketID platform2.ID d execute.Dataset fn *execute.RowMapFn cache execute.TableBuilderCache @@ -279,7 +282,7 @@ func (t *ToTransformation) RetractTable(id execute.DatasetID, key flux.GroupKey) func NewToTransformation(ctx context.Context, d execute.Dataset, cache execute.TableBuilderCache, toSpec *ToProcedureSpec, deps ToDependencies) (x *ToTransformation, err error) { var fn *execute.RowMapFn spec := toSpec.Spec - var bucketID, orgID *platform.ID + var bucketID, orgID *platform2.ID if spec.FieldFn.Fn != nil { fn = execute.NewRowMapFn(spec.FieldFn.Fn, compiler.ToScope(spec.FieldFn.Scope)) } @@ -294,15 +297,15 @@ func NewToTransformation(ctx context.Context, d execute.Dataset, cache execute.T } orgID = &oID } else if spec.OrgID != "" { - if orgID, err = platform.IDFromString(spec.OrgID); err != nil { + if orgID, err = platform2.IDFromString(spec.OrgID); err != nil { return nil, err } } else { // No org or orgID provided as an arg, use the orgID from the context req := query.RequestFromContext(ctx) if req == nil { - return nil, &platform.Error{ - Code: platform.EInternal, + return nil, &errors.Error{ + Code: errors.EInternal, Msg: "missing request on context", Op: toOp, } @@ -320,7 +323,7 @@ func NewToTransformation(ctx context.Context, d execute.Dataset, cache execute.T } } bucketID = &bID - } else if bucketID, err = platform.IDFromString(spec.BucketID); err != nil { + } else if bucketID, err = platform2.IDFromString(spec.BucketID); err != nil { return nil, &flux.Error{ Code: codes.Invalid, Msg: "invalid bucket id", @@ -466,22 +469,22 @@ type ToDependencies struct { // Validate returns an error if any required field is unset. func (d ToDependencies) Validate() error { if d.BucketLookup == nil { - return &platform.Error{ - Code: platform.EInternal, + return &errors.Error{ + Code: errors.EInternal, Msg: "missing bucket lookup dependency", Op: toOp, } } if d.OrganizationLookup == nil { - return &platform.Error{ - Code: platform.EInternal, + return &errors.Error{ + Code: errors.EInternal, Msg: "missing organization lookup dependency", Op: toOp, } } if d.PointsWriter == nil { - return &platform.Error{ - Code: platform.EInternal, + return &errors.Error{ + Code: errors.EInternal, Msg: "missing points writer dependency", Op: toOp, } @@ -589,8 +592,8 @@ func writeTable(ctx context.Context, t *ToTransformation, tbl flux.Table) (err e pointTime = valueTime.Time().Time() case isTag[j]: if col.Type != flux.TString { - return &platform.Error{ - Code: platform.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "invalid type for tag column", Op: toOp, } diff --git a/query/stdlib/influxdata/influxdb/v1/databases.go b/query/stdlib/influxdata/influxdb/v1/databases.go index 230cfaa2bd8..bdb1e97f0f2 100644 --- a/query/stdlib/influxdata/influxdb/v1/databases.go +++ b/query/stdlib/influxdata/influxdb/v1/databases.go @@ -5,6 +5,9 @@ import ( "fmt" "time" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/flux" "github.com/influxdata/flux/codes" "github.com/influxdata/flux/execute" @@ -38,7 +41,7 @@ func (s *LocalDatabasesProcedureSpec) Copy() plan.ProcedureSpec { } type DatabasesDecoder struct { - orgID platform.ID + orgID platform2.ID deps *DatabasesDependencies databases []*platform.DBRPMappingV2 alloc *memory.Allocator @@ -67,8 +70,8 @@ func (bd *DatabasesDecoder) Decode(ctx context.Context) (flux.Table, error) { for _, db := range bd.databases { bucket, err := bd.deps.BucketLookup.FindBucketByID(ctx, db.BucketID) if err != nil { - code := platform.ErrorCode(err) - if code == platform.EUnauthorized || code == platform.EForbidden { + code := errors2.ErrorCode(err) + if code == errors2.EUnauthorized || code == errors2.EForbidden { continue } return nil, err @@ -80,8 +83,8 @@ func (bd *DatabasesDecoder) Decode(ctx context.Context) (flux.Table, error) { } if len(databases) == 0 { - return nil, &platform.Error{ - Code: platform.ENotFound, + return nil, &errors2.Error{ + Code: errors2.ENotFound, Msg: "no 1.x databases found", } } diff --git a/query/storage.go b/query/storage.go index a745038c4b6..9338aa3660a 100644 --- a/query/storage.go +++ b/query/storage.go @@ -4,11 +4,12 @@ import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/flux" "github.com/influxdata/flux/execute" "github.com/influxdata/flux/memory" "github.com/influxdata/flux/plan" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/storage/reads/datatypes" "github.com/influxdata/influxdb/v2/tsdb/cursors" ) @@ -26,8 +27,8 @@ type StorageReader interface { } type ReadFilterSpec struct { - OrganizationID influxdb.ID - BucketID influxdb.ID + OrganizationID platform.ID + BucketID platform.ID Bounds execute.Bounds Predicate *datatypes.Predicate diff --git a/rand/id.go b/rand/id.go index c8ffb1ee2cc..ef8b451acee 100644 --- a/rand/id.go +++ b/rand/id.go @@ -5,10 +5,10 @@ import ( "math/rand" "sync" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" ) -var _ influxdb.IDGenerator = (*OrgBucketID)(nil) +var _ platform.IDGenerator = (*OrgBucketID)(nil) // OrgBucketID creates an id that does not have ascii // backslash, commas, or spaces. Used to create IDs for organizations @@ -46,13 +46,13 @@ func (r *OrgBucketID) Seed(seed int64) { } // ID generates an ID that does not have backslashes, commas, or spaces. -func (r *OrgBucketID) ID() influxdb.ID { +func (r *OrgBucketID) ID() platform.ID { r.m.Lock() n := r.src.Uint64() r.m.Unlock() n = sanitize(n) - return influxdb.ID(n) + return platform.ID(n) } func sanitize(n uint64) uint64 { diff --git a/rand/id_test.go b/rand/id_test.go index 82c57f46ccd..0879b1e77cd 100644 --- a/rand/id_test.go +++ b/rand/id_test.go @@ -5,24 +5,24 @@ import ( "reflect" "testing" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" ) func TestOrgBucketID_ID(t *testing.T) { tests := []struct { name string seed int64 - want influxdb.ID + want platform.ID }{ { name: "when seeded with 6 the first random number contains characters", seed: 6, - want: influxdb.ID(0xaddff35d7fe88f15), + want: platform.ID(0xaddff35d7fe88f15), }, { name: "when seeded with 1234567890 we get a random number without any bad chars", seed: 1234567890, - want: influxdb.ID(0x8a95c1bf40518fee), + want: platform.ID(0x8a95c1bf40518fee), }, } for _, tt := range tests { diff --git a/resource/resource.go b/resource/resource.go index 86a55d5d63a..d207332506b 100644 --- a/resource/resource.go +++ b/resource/resource.go @@ -7,6 +7,8 @@ package resource import ( "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -21,13 +23,13 @@ type Change struct { // Type of change. Type ChangeType // ResourceID of the changed resource. - ResourceID influxdb.ID + ResourceID platform.ID // ResourceType that was changed. ResourceType influxdb.ResourceType // OrganizationID of the organization owning the changed resource. - OrganizationID influxdb.ID + OrganizationID platform.ID // UserID of the user changing the resource. - UserID influxdb.ID + UserID platform.ID // ResourceBody after the change. ResourceBody []byte // Time when the resource was changed. diff --git a/restore/restore.go b/restore/restore.go index 37317e845b9..1f074e89245 100644 --- a/restore/restore.go +++ b/restore/restore.go @@ -11,6 +11,9 @@ import ( "sort" "strings" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/bolt" "github.com/influxdata/influxdb/v2/tenant" @@ -24,7 +27,7 @@ type Request struct { // Original ID/name of the organization to restore. // If not set, all orgs will be restored. - OrgID influxdb.ID + OrgID platform.ID Org string // New name to use for the restored organization. @@ -33,7 +36,7 @@ type Request struct { // Original ID/name of the bucket to restore. // If not set, all buckets within the org filter will be restored. - BucketID influxdb.ID + BucketID platform.ID Bucket string // New name to use for the restored bucket. @@ -241,7 +244,7 @@ func (r *restoreRunner) restoreOrganization(ctx context.Context, org *influxdb.O ) // Create organization on server if it doesn't already exist. - if o, err := r.OrgService.FindOrganization(ctx, influxdb.OrganizationFilter{Name: &newOrg.Name}); influxdb.ErrorCode(err) == influxdb.ENotFound { + if o, err := r.OrgService.FindOrganization(ctx, influxdb.OrganizationFilter{Name: &newOrg.Name}); errors.ErrorCode(err) == errors.ENotFound { if err := r.OrgService.CreateOrganization(ctx, &newOrg); err != nil { return fmt.Errorf("failed to create organization %q: %w", newOrg.Name, err) } diff --git a/scraper.go b/scraper.go index a7dac385e81..71fcd7cd888 100644 --- a/scraper.go +++ b/scraper.go @@ -2,6 +2,8 @@ package influxdb import ( "context" + + "github.com/influxdata/influxdb/v2/kit/platform" ) // ErrScraperTargetNotFound is the error msg for a missing scraper target. @@ -18,30 +20,30 @@ const ( // ScraperTarget is a target to scrape type ScraperTarget struct { - ID ID `json:"id,omitempty"` + ID platform.ID `json:"id,omitempty"` Name string `json:"name"` Type ScraperType `json:"type"` URL string `json:"url"` - OrgID ID `json:"orgID,omitempty"` - BucketID ID `json:"bucketID,omitempty"` + OrgID platform.ID `json:"orgID,omitempty"` + BucketID platform.ID `json:"bucketID,omitempty"` AllowInsecure bool `json:"allowInsecure,omitempty"` } // ScraperTargetStoreService defines the crud service for ScraperTarget. type ScraperTargetStoreService interface { ListTargets(ctx context.Context, filter ScraperTargetFilter) ([]ScraperTarget, error) - AddTarget(ctx context.Context, t *ScraperTarget, userID ID) error - GetTargetByID(ctx context.Context, id ID) (*ScraperTarget, error) - RemoveTarget(ctx context.Context, id ID) error - UpdateTarget(ctx context.Context, t *ScraperTarget, userID ID) (*ScraperTarget, error) + AddTarget(ctx context.Context, t *ScraperTarget, userID platform.ID) error + GetTargetByID(ctx context.Context, id platform.ID) (*ScraperTarget, error) + RemoveTarget(ctx context.Context, id platform.ID) error + UpdateTarget(ctx context.Context, t *ScraperTarget, userID platform.ID) (*ScraperTarget, error) } // ScraperTargetFilter represents a set of filter that restrict the returned results. type ScraperTargetFilter struct { - IDs map[ID]bool `json:"ids"` - Name *string `json:"name"` - OrgID *ID `json:"orgID"` - Org *string `json:"org"` + IDs map[platform.ID]bool `json:"ids"` + Name *string `json:"name"` + OrgID *platform.ID `json:"orgID"` + Org *string `json:"org"` } // ScraperType defines the scraper methods. diff --git a/secret.go b/secret.go index 9c6686b30ba..719408bc3b8 100644 --- a/secret.go +++ b/secret.go @@ -4,6 +4,8 @@ import ( "context" "encoding/json" "strings" + + "github.com/influxdata/influxdb/v2/kit/platform" ) // ErrSecretNotFound is the error msg for a missing secret. @@ -12,22 +14,22 @@ const ErrSecretNotFound = "secret not found" // SecretService a service for storing and retrieving secrets. type SecretService interface { // LoadSecret retrieves the secret value v found at key k for organization orgID. - LoadSecret(ctx context.Context, orgID ID, k string) (string, error) + LoadSecret(ctx context.Context, orgID platform.ID, k string) (string, error) // GetSecretKeys retrieves all secret keys that are stored for the organization orgID. - GetSecretKeys(ctx context.Context, orgID ID) ([]string, error) + GetSecretKeys(ctx context.Context, orgID platform.ID) ([]string, error) // PutSecret stores the secret pair (k,v) for the organization orgID. - PutSecret(ctx context.Context, orgID ID, k string, v string) error + PutSecret(ctx context.Context, orgID platform.ID, k string, v string) error // PutSecrets puts all provided secrets and overwrites any previous values. - PutSecrets(ctx context.Context, orgID ID, m map[string]string) error + PutSecrets(ctx context.Context, orgID platform.ID, m map[string]string) error // PatchSecrets patches all provided secrets and updates any previous values. - PatchSecrets(ctx context.Context, orgID ID, m map[string]string) error + PatchSecrets(ctx context.Context, orgID platform.ID, m map[string]string) error // DeleteSecret removes a single secret from the secret store. - DeleteSecret(ctx context.Context, orgID ID, ks ...string) error + DeleteSecret(ctx context.Context, orgID platform.ID, ks ...string) error } // SecretField contains a key string, and value pointer. diff --git a/secret/http_client.go b/secret/http_client.go index 312fa4acb16..ef3f268b64e 100644 --- a/secret/http_client.go +++ b/secret/http_client.go @@ -4,7 +4,9 @@ import ( "context" "fmt" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2/kit/tracing" "github.com/influxdata/influxdb/v2/pkg/httpc" ) @@ -14,23 +16,23 @@ type Client struct { } // LoadSecret is not implemented for http -func (s *Client) LoadSecret(ctx context.Context, orgID influxdb.ID, k string) (string, error) { - return "", &influxdb.Error{ - Code: influxdb.EMethodNotAllowed, +func (s *Client) LoadSecret(ctx context.Context, orgID platform.ID, k string) (string, error) { + return "", &errors.Error{ + Code: errors.EMethodNotAllowed, Msg: "load secret is not implemented for http", } } // PutSecret is not implemented for http. -func (s *Client) PutSecret(ctx context.Context, orgID influxdb.ID, k string, v string) error { - return &influxdb.Error{ - Code: influxdb.EMethodNotAllowed, +func (s *Client) PutSecret(ctx context.Context, orgID platform.ID, k string, v string) error { + return &errors.Error{ + Code: errors.EMethodNotAllowed, Msg: "put secret is not implemented for http", } } // GetSecretKeys get all secret keys mathing an org ID via HTTP. -func (s *Client) GetSecretKeys(ctx context.Context, orgID influxdb.ID) ([]string, error) { +func (s *Client) GetSecretKeys(ctx context.Context, orgID platform.ID) ([]string, error) { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -51,15 +53,15 @@ func (s *Client) GetSecretKeys(ctx context.Context, orgID influxdb.ID) ([]string } // PutSecrets is not implemented for http. -func (s *Client) PutSecrets(ctx context.Context, orgID influxdb.ID, m map[string]string) error { - return &influxdb.Error{ - Code: influxdb.EMethodNotAllowed, +func (s *Client) PutSecrets(ctx context.Context, orgID platform.ID, m map[string]string) error { + return &errors.Error{ + Code: errors.EMethodNotAllowed, Msg: "put secrets is not implemented for http", } } // PatchSecrets will update the existing secret with new via http. -func (s *Client) PatchSecrets(ctx context.Context, orgID influxdb.ID, m map[string]string) error { +func (s *Client) PatchSecrets(ctx context.Context, orgID platform.ID, m map[string]string) error { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -75,7 +77,7 @@ func (s *Client) PatchSecrets(ctx context.Context, orgID influxdb.ID, m map[stri } // DeleteSecret removes a single secret via HTTP. -func (s *Client) DeleteSecret(ctx context.Context, orgID influxdb.ID, ks ...string) error { +func (s *Client) DeleteSecret(ctx context.Context, orgID platform.ID, ks ...string) error { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() diff --git a/secret/http_server.go b/secret/http_server.go index efe27a9116e..08f6d990bf1 100644 --- a/secret/http_server.go +++ b/secret/http_server.go @@ -4,6 +4,9 @@ import ( "fmt" "net/http" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" "github.com/influxdata/influxdb/v2" kithttp "github.com/influxdata/influxdb/v2/kit/transport/http" @@ -45,7 +48,7 @@ func (h *handler) handleGetSecrets(w http.ResponseWriter, r *http.Request) { } ks, err := h.svc.GetSecretKeys(r.Context(), orgID) - if err != nil && influxdb.ErrorCode(err) != influxdb.ENotFound { + if err != nil && errors.ErrorCode(err) != errors.ENotFound { h.api.Err(w, r, err) return } @@ -58,7 +61,7 @@ type secretsResponse struct { Secrets []string `json:"secrets"` } -func newSecretsResponse(orgID influxdb.ID, ks []string) *secretsResponse { +func newSecretsResponse(orgID platform.ID, ks []string) *secretsResponse { if ks == nil { ks = []string{} } @@ -118,17 +121,17 @@ func (h *handler) handleDeleteSecrets(w http.ResponseWriter, r *http.Request) { h.api.Respond(w, r, http.StatusNoContent, nil) } -func (h *handler) decodeOrgID(r *http.Request) (influxdb.ID, error) { +func (h *handler) decodeOrgID(r *http.Request) (platform.ID, error) { org := chi.URLParam(r, h.idLookupKey) if org == "" { - return influxdb.InvalidID(), &influxdb.Error{ - Code: influxdb.EInvalid, + return platform.InvalidID(), &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - id, err := influxdb.IDFromString(org) + id, err := platform.IDFromString(org) if err != nil { - return influxdb.InvalidID(), err + return platform.InvalidID(), err } return *id, nil } diff --git a/secret/http_server_test.go b/secret/http_server_test.go index ab12c7dcb01..ed20e1a451c 100644 --- a/secret/http_server_test.go +++ b/secret/http_server_test.go @@ -10,6 +10,9 @@ import ( "net/http/httptest" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" "github.com/influxdata/influxdb/v2" influxdbhttp "github.com/influxdata/influxdb/v2/http" @@ -73,7 +76,7 @@ func TestSecretService_handleGetSecrets(t *testing.T) { SecretService influxdb.SecretService } type args struct { - orgID influxdb.ID + orgID platform.ID } type wants struct { statusCode int @@ -91,7 +94,7 @@ func TestSecretService_handleGetSecrets(t *testing.T) { name: "get basic secrets", fields: fields{ &mock.SecretService{ - GetSecretKeysFn: func(ctx context.Context, orgID influxdb.ID) ([]string, error) { + GetSecretKeysFn: func(ctx context.Context, orgID platform.ID) ([]string, error) { return []string{"hello", "world"}, nil }, }, @@ -109,7 +112,7 @@ func TestSecretService_handleGetSecrets(t *testing.T) { name: "get secrets when there are none", fields: fields{ &mock.SecretService{ - GetSecretKeysFn: func(ctx context.Context, orgID influxdb.ID) ([]string, error) { + GetSecretKeysFn: func(ctx context.Context, orgID platform.ID) ([]string, error) { return []string{}, nil }, }, @@ -127,9 +130,9 @@ func TestSecretService_handleGetSecrets(t *testing.T) { name: "get secrets when organization has no secret keys", fields: fields{ &mock.SecretService{ - GetSecretKeysFn: func(ctx context.Context, orgID influxdb.ID) ([]string, error) { - return []string{}, &influxdb.Error{ - Code: influxdb.ENotFound, + GetSecretKeysFn: func(ctx context.Context, orgID platform.ID) ([]string, error) { + return []string{}, &errors.Error{ + Code: errors.ENotFound, Msg: "organization has no secret keys", } @@ -183,7 +186,7 @@ func TestSecretService_handlePatchSecrets(t *testing.T) { SecretService influxdb.SecretService } type args struct { - orgID influxdb.ID + orgID platform.ID secrets map[string]string } type wants struct { @@ -202,7 +205,7 @@ func TestSecretService_handlePatchSecrets(t *testing.T) { name: "get basic secrets", fields: fields{ &mock.SecretService{ - PatchSecretsFn: func(ctx context.Context, orgID influxdb.ID, s map[string]string) error { + PatchSecretsFn: func(ctx context.Context, orgID platform.ID, s map[string]string) error { return nil }, }, @@ -262,7 +265,7 @@ func TestSecretService_handleDeleteSecrets(t *testing.T) { SecretService influxdb.SecretService } type args struct { - orgID influxdb.ID + orgID platform.ID secrets []string } type wants struct { @@ -281,7 +284,7 @@ func TestSecretService_handleDeleteSecrets(t *testing.T) { name: "get basic secrets", fields: fields{ &mock.SecretService{ - DeleteSecretFn: func(ctx context.Context, orgID influxdb.ID, s ...string) error { + DeleteSecretFn: func(ctx context.Context, orgID platform.ID, s ...string) error { return nil }, }, diff --git a/secret/middleware_auth.go b/secret/middleware_auth.go index fa508286b47..891314764e4 100644 --- a/secret/middleware_auth.go +++ b/secret/middleware_auth.go @@ -3,6 +3,8 @@ package secret import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/authorizer" ) @@ -23,7 +25,7 @@ func NewAuthedService(s influxdb.SecretService) *AuthedSvc { } // LoadSecret checks to see if the authorizer on context has read access to the secret key provided. -func (s *AuthedSvc) LoadSecret(ctx context.Context, orgID influxdb.ID, key string) (string, error) { +func (s *AuthedSvc) LoadSecret(ctx context.Context, orgID platform.ID, key string) (string, error) { if _, _, err := authorizer.AuthorizeOrgReadResource(ctx, influxdb.SecretsResourceType, orgID); err != nil { return "", err } @@ -35,7 +37,7 @@ func (s *AuthedSvc) LoadSecret(ctx context.Context, orgID influxdb.ID, key strin } // GetSecretKeys checks to see if the authorizer on context has read access to all the secrets belonging to orgID. -func (s *AuthedSvc) GetSecretKeys(ctx context.Context, orgID influxdb.ID) ([]string, error) { +func (s *AuthedSvc) GetSecretKeys(ctx context.Context, orgID platform.ID) ([]string, error) { if _, _, err := authorizer.AuthorizeOrgReadResource(ctx, influxdb.SecretsResourceType, orgID); err != nil { return []string{}, err } @@ -47,7 +49,7 @@ func (s *AuthedSvc) GetSecretKeys(ctx context.Context, orgID influxdb.ID) ([]str } // PutSecret checks to see if the authorizer on context has write access to the secret key provided. -func (s *AuthedSvc) PutSecret(ctx context.Context, orgID influxdb.ID, key string, val string) error { +func (s *AuthedSvc) PutSecret(ctx context.Context, orgID platform.ID, key string, val string) error { if _, _, err := authorizer.AuthorizeCreate(ctx, influxdb.SecretsResourceType, orgID); err != nil { return err } @@ -59,7 +61,7 @@ func (s *AuthedSvc) PutSecret(ctx context.Context, orgID influxdb.ID, key string } // PutSecrets checks to see if the authorizer on context has read and write access to the secret keys provided. -func (s *AuthedSvc) PutSecrets(ctx context.Context, orgID influxdb.ID, m map[string]string) error { +func (s *AuthedSvc) PutSecrets(ctx context.Context, orgID platform.ID, m map[string]string) error { // PutSecrets operates on intersection between m and keys beloging to orgID. // We need to have read access to those secrets since it deletes the secrets (within the intersection) that have not be overridden. if _, _, err := authorizer.AuthorizeOrgReadResource(ctx, influxdb.SecretsResourceType, orgID); err != nil { @@ -76,7 +78,7 @@ func (s *AuthedSvc) PutSecrets(ctx context.Context, orgID influxdb.ID, m map[str } // PatchSecrets checks to see if the authorizer on context has write access to the secret keys provided. -func (s *AuthedSvc) PatchSecrets(ctx context.Context, orgID influxdb.ID, m map[string]string) error { +func (s *AuthedSvc) PatchSecrets(ctx context.Context, orgID platform.ID, m map[string]string) error { if _, _, err := authorizer.AuthorizeOrgWriteResource(ctx, influxdb.SecretsResourceType, orgID); err != nil { return err } @@ -88,7 +90,7 @@ func (s *AuthedSvc) PatchSecrets(ctx context.Context, orgID influxdb.ID, m map[s } // DeleteSecret checks to see if the authorizer on context has write access to the secret keys provided. -func (s *AuthedSvc) DeleteSecret(ctx context.Context, orgID influxdb.ID, keys ...string) error { +func (s *AuthedSvc) DeleteSecret(ctx context.Context, orgID platform.ID, keys ...string) error { if _, _, err := authorizer.AuthorizeOrgWriteResource(ctx, influxdb.SecretsResourceType, orgID); err != nil { return err } diff --git a/secret/middleware_auth_test.go b/secret/middleware_auth_test.go index c9973f90908..8dcedd98467 100644 --- a/secret/middleware_auth_test.go +++ b/secret/middleware_auth_test.go @@ -3,6 +3,8 @@ package secret_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "testing" "github.com/google/go-cmp/cmp" @@ -25,7 +27,7 @@ func TestSecretService_LoadSecret(t *testing.T) { } type args struct { permission influxdb.Permission - org influxdb.ID + org platform.ID key string } type wants struct { @@ -42,12 +44,12 @@ func TestSecretService_LoadSecret(t *testing.T) { name: "authorized to access secret within org", fields: fields{ SecretService: &mock.SecretService{ - LoadSecretFn: func(ctx context.Context, orgID influxdb.ID, k string) (string, error) { + LoadSecretFn: func(ctx context.Context, orgID platform.ID, k string) (string, error) { if k == "key" { return "val", nil } - return "", &influxdb.Error{ - Code: influxdb.ENotFound, + return "", &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrSecretNotFound, } }, @@ -62,7 +64,7 @@ func TestSecretService_LoadSecret(t *testing.T) { }, }, key: "key", - org: influxdb.ID(10), + org: platform.ID(10), }, wants: wants{ err: nil, @@ -72,12 +74,12 @@ func TestSecretService_LoadSecret(t *testing.T) { name: "cannot access not existing secret", fields: fields{ SecretService: &mock.SecretService{ - LoadSecretFn: func(ctx context.Context, orgID influxdb.ID, k string) (string, error) { + LoadSecretFn: func(ctx context.Context, orgID platform.ID, k string) (string, error) { if k == "key" { return "val", nil } - return "", &influxdb.Error{ - Code: influxdb.ENotFound, + return "", &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrSecretNotFound, } }, @@ -92,11 +94,11 @@ func TestSecretService_LoadSecret(t *testing.T) { }, }, key: "not existing", - org: influxdb.ID(10), + org: platform.ID(10), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrSecretNotFound, }, }, @@ -105,12 +107,12 @@ func TestSecretService_LoadSecret(t *testing.T) { name: "unauthorized to access secret within org", fields: fields{ SecretService: &mock.SecretService{ - LoadSecretFn: func(ctx context.Context, orgID influxdb.ID, k string) (string, error) { + LoadSecretFn: func(ctx context.Context, orgID platform.ID, k string) (string, error) { if k == "key" { return "val", nil } - return "", &influxdb.Error{ - Code: influxdb.ENotFound, + return "", &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrSecretNotFound, } }, @@ -124,13 +126,13 @@ func TestSecretService_LoadSecret(t *testing.T) { ID: influxdbtesting.IDPtr(10), }, }, - org: influxdb.ID(2), + org: platform.ID(2), key: "key", }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/0000000000000002/secrets is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -155,7 +157,7 @@ func TestSecretService_GetSecretKeys(t *testing.T) { } type args struct { permission influxdb.Permission - org influxdb.ID + org platform.ID } type wants struct { err error @@ -172,7 +174,7 @@ func TestSecretService_GetSecretKeys(t *testing.T) { name: "authorized to see all secrets within an org", fields: fields{ SecretService: &mock.SecretService{ - GetSecretKeysFn: func(ctx context.Context, orgID influxdb.ID) ([]string, error) { + GetSecretKeysFn: func(ctx context.Context, orgID platform.ID) ([]string, error) { return []string{ "0000000000000001secret1", "0000000000000001secret2", @@ -189,7 +191,7 @@ func TestSecretService_GetSecretKeys(t *testing.T) { OrgID: influxdbtesting.IDPtr(1), }, }, - org: influxdb.ID(1), + org: platform.ID(1), }, wants: wants{ secrets: []string{ @@ -203,7 +205,7 @@ func TestSecretService_GetSecretKeys(t *testing.T) { name: "unauthorized to see all secrets within an org", fields: fields{ SecretService: &mock.SecretService{ - GetSecretKeysFn: func(ctx context.Context, orgID influxdb.ID) ([]string, error) { + GetSecretKeysFn: func(ctx context.Context, orgID platform.ID) ([]string, error) { return []string{ "0000000000000002secret1", "0000000000000002secret2", @@ -220,11 +222,11 @@ func TestSecretService_GetSecretKeys(t *testing.T) { OrgID: influxdbtesting.IDPtr(1), }, }, - org: influxdb.ID(2), + org: platform.ID(2), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EUnauthorized, + err: &errors.Error{ + Code: errors.EUnauthorized, Msg: "read:orgs/0000000000000002/secrets is unauthorized", }, secrets: []string{}, @@ -234,9 +236,9 @@ func TestSecretService_GetSecretKeys(t *testing.T) { name: "errors when there are not secret into an org", fields: fields{ SecretService: &mock.SecretService{ - GetSecretKeysFn: func(ctx context.Context, orgID influxdb.ID) ([]string, error) { - return []string(nil), &influxdb.Error{ - Code: influxdb.ENotFound, + GetSecretKeysFn: func(ctx context.Context, orgID platform.ID) ([]string, error) { + return []string(nil), &errors.Error{ + Code: errors.ENotFound, Msg: "organization has no secret keys", } }, @@ -250,11 +252,11 @@ func TestSecretService_GetSecretKeys(t *testing.T) { OrgID: influxdbtesting.IDPtr(10), }, }, - org: influxdb.ID(10), + org: platform.ID(10), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "organization has no secret keys", }, secrets: []string{}, @@ -284,7 +286,7 @@ func TestSecretService_PatchSecrets(t *testing.T) { SecretService influxdb.SecretService } type args struct { - org influxdb.ID + org platform.ID permissions []influxdb.Permission } type wants struct { @@ -301,13 +303,13 @@ func TestSecretService_PatchSecrets(t *testing.T) { name: "authorized to patch secrets", fields: fields{ SecretService: &mock.SecretService{ - PatchSecretsFn: func(ctx context.Context, orgID influxdb.ID, m map[string]string) error { + PatchSecretsFn: func(ctx context.Context, orgID platform.ID, m map[string]string) error { return nil }, }, }, args: args{ - org: influxdb.ID(1), + org: platform.ID(1), permissions: []influxdb.Permission{ { Action: influxdb.WriteAction, @@ -326,13 +328,13 @@ func TestSecretService_PatchSecrets(t *testing.T) { name: "unauthorized to update secret", fields: fields{ SecretService: &mock.SecretService{ - PatchSecretsFn: func(ctx context.Context, orgID influxdb.ID, m map[string]string) error { + PatchSecretsFn: func(ctx context.Context, orgID platform.ID, m map[string]string) error { return nil }, }, }, args: args{ - org: influxdb.ID(1), + org: platform.ID(1), permissions: []influxdb.Permission{ { Action: influxdb.ReadAction, @@ -344,9 +346,9 @@ func TestSecretService_PatchSecrets(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/0000000000000001/secrets is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -371,7 +373,7 @@ func TestSecretService_DeleteSecret(t *testing.T) { SecretService influxdb.SecretService } type args struct { - org influxdb.ID + org platform.ID permissions []influxdb.Permission } type wants struct { @@ -388,13 +390,13 @@ func TestSecretService_DeleteSecret(t *testing.T) { name: "authorized to delete secret", fields: fields{ SecretService: &mock.SecretService{ - DeleteSecretFn: func(ctx context.Context, orgID influxdb.ID, keys ...string) error { + DeleteSecretFn: func(ctx context.Context, orgID platform.ID, keys ...string) error { return nil }, }, }, args: args{ - org: influxdb.ID(1), + org: platform.ID(1), permissions: []influxdb.Permission{ { Action: influxdb.WriteAction, @@ -413,7 +415,7 @@ func TestSecretService_DeleteSecret(t *testing.T) { name: "unauthorized to delete secret", fields: fields{ SecretService: &mock.SecretService{ - DeleteSecretFn: func(ctx context.Context, orgID influxdb.ID, keys ...string) error { + DeleteSecretFn: func(ctx context.Context, orgID platform.ID, keys ...string) error { return nil }, }, @@ -431,9 +433,9 @@ func TestSecretService_DeleteSecret(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/secrets is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -458,7 +460,7 @@ func TestSecretService_PutSecret(t *testing.T) { } type args struct { permission influxdb.Permission - orgID influxdb.ID + orgID platform.ID } type wants struct { err error @@ -474,13 +476,13 @@ func TestSecretService_PutSecret(t *testing.T) { name: "authorized to put a secret", fields: fields{ SecretService: &mock.SecretService{ - PutSecretFn: func(ctx context.Context, orgID influxdb.ID, key string, val string) error { + PutSecretFn: func(ctx context.Context, orgID platform.ID, key string, val string) error { return nil }, }, }, args: args{ - orgID: influxdb.ID(10), + orgID: platform.ID(10), permission: influxdb.Permission{ Action: influxdb.WriteAction, Resource: influxdb.Resource{ @@ -497,7 +499,7 @@ func TestSecretService_PutSecret(t *testing.T) { name: "unauthorized to put a secret", fields: fields{ SecretService: &mock.SecretService{ - PutSecretFn: func(ctx context.Context, orgID influxdb.ID, key string, val string) error { + PutSecretFn: func(ctx context.Context, orgID platform.ID, key string, val string) error { return nil }, }, @@ -513,9 +515,9 @@ func TestSecretService_PutSecret(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/secrets is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -540,7 +542,7 @@ func TestSecretService_PutSecrets(t *testing.T) { } type args struct { permissions []influxdb.Permission - orgID influxdb.ID + orgID platform.ID } type wants struct { err error @@ -556,13 +558,13 @@ func TestSecretService_PutSecrets(t *testing.T) { name: "authorized to put secrets", fields: fields{ SecretService: &mock.SecretService{ - PutSecretsFn: func(ctx context.Context, orgID influxdb.ID, m map[string]string) error { + PutSecretsFn: func(ctx context.Context, orgID platform.ID, m map[string]string) error { return nil }, }, }, args: args{ - orgID: influxdb.ID(10), + orgID: platform.ID(10), permissions: []influxdb.Permission{ { Action: influxdb.WriteAction, @@ -588,13 +590,13 @@ func TestSecretService_PutSecrets(t *testing.T) { name: "unauthorized to put secrets", fields: fields{ SecretService: &mock.SecretService{ - PutSecretsFn: func(ctx context.Context, orgID influxdb.ID, m map[string]string) error { + PutSecretsFn: func(ctx context.Context, orgID platform.ID, m map[string]string) error { return nil }, }, }, args: args{ - orgID: influxdb.ID(2), + orgID: platform.ID(2), permissions: []influxdb.Permission{ { Action: influxdb.WriteAction, @@ -613,9 +615,9 @@ func TestSecretService_PutSecrets(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/0000000000000002/secrets is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -623,10 +625,10 @@ func TestSecretService_PutSecrets(t *testing.T) { name: "unauthorized to put secrets without read access to their org", fields: fields{ SecretService: &mock.SecretService{ - PutSecretFn: func(ctx context.Context, orgID influxdb.ID, key string, val string) error { + PutSecretFn: func(ctx context.Context, orgID platform.ID, key string, val string) error { return nil }, - PutSecretsFn: func(ctx context.Context, orgID influxdb.ID, m map[string]string) error { + PutSecretsFn: func(ctx context.Context, orgID platform.ID, m map[string]string) error { return nil }, }, @@ -644,9 +646,9 @@ func TestSecretService_PutSecrets(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/000000000000000a/secrets is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -654,10 +656,10 @@ func TestSecretService_PutSecrets(t *testing.T) { name: "unauthorized to put secrets without write access to their org", fields: fields{ SecretService: &mock.SecretService{ - PutSecretFn: func(ctx context.Context, orgID influxdb.ID, key string, val string) error { + PutSecretFn: func(ctx context.Context, orgID platform.ID, key string, val string) error { return nil }, - PutSecretsFn: func(ctx context.Context, orgID influxdb.ID, m map[string]string) error { + PutSecretsFn: func(ctx context.Context, orgID platform.ID, m map[string]string) error { return nil }, }, @@ -675,9 +677,9 @@ func TestSecretService_PutSecrets(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/secrets is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, diff --git a/secret/middleware_logging.go b/secret/middleware_logging.go index 97d9b9d7249..26fe546868e 100644 --- a/secret/middleware_logging.go +++ b/secret/middleware_logging.go @@ -4,6 +4,8 @@ import ( "context" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "go.uber.org/zap" ) @@ -25,7 +27,7 @@ func NewLogger(log *zap.Logger, s influxdb.SecretService) *Logger { } // LoadSecret retrieves the secret value v found at key k for organization orgID. -func (l *Logger) LoadSecret(ctx context.Context, orgID influxdb.ID, key string) (str string, err error) { +func (l *Logger) LoadSecret(ctx context.Context, orgID platform.ID, key string) (str string, err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -39,7 +41,7 @@ func (l *Logger) LoadSecret(ctx context.Context, orgID influxdb.ID, key string) } // GetSecretKeys retrieves all secret keys that are stored for the organization orgID. -func (l *Logger) GetSecretKeys(ctx context.Context, orgID influxdb.ID) (strs []string, err error) { +func (l *Logger) GetSecretKeys(ctx context.Context, orgID platform.ID) (strs []string, err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -53,7 +55,7 @@ func (l *Logger) GetSecretKeys(ctx context.Context, orgID influxdb.ID) (strs []s } // PutSecret stores the secret pair (k,v) for the organization orgID. -func (l *Logger) PutSecret(ctx context.Context, orgID influxdb.ID, key string, val string) (err error) { +func (l *Logger) PutSecret(ctx context.Context, orgID platform.ID, key string, val string) (err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -67,7 +69,7 @@ func (l *Logger) PutSecret(ctx context.Context, orgID influxdb.ID, key string, v } // PutSecrets puts all provided secrets and overwrites any previous values. -func (l *Logger) PutSecrets(ctx context.Context, orgID influxdb.ID, m map[string]string) (err error) { +func (l *Logger) PutSecrets(ctx context.Context, orgID platform.ID, m map[string]string) (err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -81,7 +83,7 @@ func (l *Logger) PutSecrets(ctx context.Context, orgID influxdb.ID, m map[string } // PatchSecrets patches all provided secrets and updates any previous values. -func (l *Logger) PatchSecrets(ctx context.Context, orgID influxdb.ID, m map[string]string) (err error) { +func (l *Logger) PatchSecrets(ctx context.Context, orgID platform.ID, m map[string]string) (err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -95,7 +97,7 @@ func (l *Logger) PatchSecrets(ctx context.Context, orgID influxdb.ID, m map[stri } // DeleteSecret removes a single secret from the secret store. -func (l *Logger) DeleteSecret(ctx context.Context, orgID influxdb.ID, keys ...string) (err error) { +func (l *Logger) DeleteSecret(ctx context.Context, orgID platform.ID, keys ...string) (err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { diff --git a/secret/middleware_metrics.go b/secret/middleware_metrics.go index d3ce60e66cf..1169a88d497 100644 --- a/secret/middleware_metrics.go +++ b/secret/middleware_metrics.go @@ -3,6 +3,8 @@ package secret import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/metric" "github.com/prometheus/client_golang/prometheus" @@ -27,42 +29,42 @@ func NewMetricService(reg prometheus.Registerer, s influxdb.SecretService) *Secr } // LoadSecret retrieves the secret value v found at key k for organization orgID. -func (ms *SecreteService) LoadSecret(ctx context.Context, orgID influxdb.ID, key string) (string, error) { +func (ms *SecreteService) LoadSecret(ctx context.Context, orgID platform.ID, key string) (string, error) { rec := ms.rec.Record("load_secret") secret, err := ms.secretSvc.LoadSecret(ctx, orgID, key) return secret, rec(err) } // GetSecretKeys retrieves all secret keys that are stored for the organization orgID. -func (ms *SecreteService) GetSecretKeys(ctx context.Context, orgID influxdb.ID) ([]string, error) { +func (ms *SecreteService) GetSecretKeys(ctx context.Context, orgID platform.ID) ([]string, error) { rec := ms.rec.Record("get_secret_keys") secrets, err := ms.secretSvc.GetSecretKeys(ctx, orgID) return secrets, rec(err) } // PutSecret stores the secret pair (k,v) for the organization orgID. -func (ms *SecreteService) PutSecret(ctx context.Context, orgID influxdb.ID, key string, val string) error { +func (ms *SecreteService) PutSecret(ctx context.Context, orgID platform.ID, key string, val string) error { rec := ms.rec.Record("put_secret") err := ms.secretSvc.PutSecret(ctx, orgID, key, val) return rec(err) } // PutSecrets puts all provided secrets and overwrites any previous values. -func (ms *SecreteService) PutSecrets(ctx context.Context, orgID influxdb.ID, m map[string]string) error { +func (ms *SecreteService) PutSecrets(ctx context.Context, orgID platform.ID, m map[string]string) error { rec := ms.rec.Record("put_secrets") err := ms.secretSvc.PutSecrets(ctx, orgID, m) return rec(err) } // PatchSecrets patches all provided secrets and updates any previous values. -func (ms *SecreteService) PatchSecrets(ctx context.Context, orgID influxdb.ID, m map[string]string) error { +func (ms *SecreteService) PatchSecrets(ctx context.Context, orgID platform.ID, m map[string]string) error { rec := ms.rec.Record("patch_secrets") err := ms.secretSvc.PatchSecrets(ctx, orgID, m) return rec(err) } // DeleteSecret removes a single secret from the secret store. -func (ms *SecreteService) DeleteSecret(ctx context.Context, orgID influxdb.ID, keys ...string) error { +func (ms *SecreteService) DeleteSecret(ctx context.Context, orgID platform.ID, keys ...string) error { rec := ms.rec.Record("delete_secret") err := ms.secretSvc.DeleteSecret(ctx, orgID, keys...) return rec(err) diff --git a/secret/service.go b/secret/service.go index 946092c3bcd..d92b6f38dba 100644 --- a/secret/service.go +++ b/secret/service.go @@ -3,7 +3,8 @@ package secret import ( "context" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kv" ) @@ -17,7 +18,7 @@ func NewService(s *Storage) *Service { } // LoadSecret retrieves the secret value v found at key k for organization orgID. -func (s *Service) LoadSecret(ctx context.Context, orgID influxdb.ID, k string) (string, error) { +func (s *Service) LoadSecret(ctx context.Context, orgID platform.ID, k string) (string, error) { var v string err := s.s.View(ctx, func(tx kv.Tx) error { var err error @@ -28,7 +29,7 @@ func (s *Service) LoadSecret(ctx context.Context, orgID influxdb.ID, k string) ( } // GetSecretKeys retrieves all secret keys that are stored for the organization orgID. -func (s *Service) GetSecretKeys(ctx context.Context, orgID influxdb.ID) ([]string, error) { +func (s *Service) GetSecretKeys(ctx context.Context, orgID platform.ID) ([]string, error) { var v []string err := s.s.View(ctx, func(tx kv.Tx) error { var err error @@ -39,7 +40,7 @@ func (s *Service) GetSecretKeys(ctx context.Context, orgID influxdb.ID) ([]strin } // PutSecret stores the secret pair (k,v) for the organization orgID. -func (s *Service) PutSecret(ctx context.Context, orgID influxdb.ID, k, v string) error { +func (s *Service) PutSecret(ctx context.Context, orgID platform.ID, k, v string) error { err := s.s.Update(ctx, func(tx kv.Tx) error { return s.s.PutSecret(ctx, tx, orgID, k, v) }) @@ -47,7 +48,7 @@ func (s *Service) PutSecret(ctx context.Context, orgID influxdb.ID, k, v string) } // PutSecrets puts all provided secrets and overwrites any previous values. -func (s *Service) PutSecrets(ctx context.Context, orgID influxdb.ID, m map[string]string) error { +func (s *Service) PutSecrets(ctx context.Context, orgID platform.ID, m map[string]string) error { // put secretes expects to replace all existing secretes keys, err := s.GetSecretKeys(ctx, orgID) if err != nil { @@ -61,7 +62,7 @@ func (s *Service) PutSecrets(ctx context.Context, orgID influxdb.ID, m map[strin } // PatchSecrets patches all provided secrets and updates any previous values. -func (s *Service) PatchSecrets(ctx context.Context, orgID influxdb.ID, m map[string]string) error { +func (s *Service) PatchSecrets(ctx context.Context, orgID platform.ID, m map[string]string) error { err := s.s.Update(ctx, func(tx kv.Tx) error { for k, v := range m { err := s.s.PutSecret(ctx, tx, orgID, k, v) @@ -75,7 +76,7 @@ func (s *Service) PatchSecrets(ctx context.Context, orgID influxdb.ID, m map[str } // DeleteSecret removes a single secret from the secret store. -func (s *Service) DeleteSecret(ctx context.Context, orgID influxdb.ID, ks ...string) error { +func (s *Service) DeleteSecret(ctx context.Context, orgID platform.ID, ks ...string) error { err := s.s.Update(ctx, func(tx kv.Tx) error { for _, k := range ks { err := s.s.DeleteSecret(ctx, tx, orgID, k) diff --git a/secret/storage.go b/secret/storage.go index bf67ae2ab4d..656c0677b0f 100644 --- a/secret/storage.go +++ b/secret/storage.go @@ -5,6 +5,9 @@ import ( "encoding/base64" "errors" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" ) @@ -31,7 +34,7 @@ func (s *Storage) Update(ctx context.Context, fn func(kv.Tx) error) error { } // GetSecret Returns the value of a secret -func (s *Storage) GetSecret(ctx context.Context, tx kv.Tx, orgID influxdb.ID, k string) (string, error) { +func (s *Storage) GetSecret(ctx context.Context, tx kv.Tx, orgID platform.ID, k string) (string, error) { key, err := encodeSecretKey(orgID, k) if err != nil { return "", err @@ -44,8 +47,8 @@ func (s *Storage) GetSecret(ctx context.Context, tx kv.Tx, orgID influxdb.ID, k val, err := b.Get(key) if kv.IsNotFound(err) { - return "", &influxdb.Error{ - Code: influxdb.ENotFound, + return "", &errors2.Error{ + Code: errors2.ENotFound, Msg: influxdb.ErrSecretNotFound, } } @@ -63,7 +66,7 @@ func (s *Storage) GetSecret(ctx context.Context, tx kv.Tx, orgID influxdb.ID, k } // ListSecrets returns a list of secret keys -func (s *Storage) ListSecret(ctx context.Context, tx kv.Tx, orgID influxdb.ID) ([]string, error) { +func (s *Storage) ListSecret(ctx context.Context, tx kv.Tx, orgID platform.ID) ([]string, error) { b, err := tx.Bucket(secretBucket) if err != nil { return nil, err @@ -104,7 +107,7 @@ func (s *Storage) ListSecret(ctx context.Context, tx kv.Tx, orgID influxdb.ID) ( } // PutSecret sets a secret in the db. -func (s *Storage) PutSecret(ctx context.Context, tx kv.Tx, orgID influxdb.ID, k, v string) error { +func (s *Storage) PutSecret(ctx context.Context, tx kv.Tx, orgID platform.ID, k, v string) error { key, err := encodeSecretKey(orgID, k) if err != nil { return err @@ -125,7 +128,7 @@ func (s *Storage) PutSecret(ctx context.Context, tx kv.Tx, orgID influxdb.ID, k, } // DeleteSecret removes a secret for the db -func (s *Storage) DeleteSecret(ctx context.Context, tx kv.Tx, orgID influxdb.ID, k string) error { +func (s *Storage) DeleteSecret(ctx context.Context, tx kv.Tx, orgID platform.ID, k string) error { key, err := encodeSecretKey(orgID, k) if err != nil { return err @@ -139,31 +142,31 @@ func (s *Storage) DeleteSecret(ctx context.Context, tx kv.Tx, orgID influxdb.ID, return b.Delete(key) } -func encodeSecretKey(orgID influxdb.ID, k string) ([]byte, error) { +func encodeSecretKey(orgID platform.ID, k string) ([]byte, error) { buf, err := orgID.Encode() if err != nil { return nil, err } - key := make([]byte, 0, influxdb.IDLength+len(k)) + key := make([]byte, 0, platform.IDLength+len(k)) key = append(key, buf...) key = append(key, k...) return key, nil } -func decodeSecretKey(key []byte) (influxdb.ID, string, error) { - if len(key) < influxdb.IDLength { +func decodeSecretKey(key []byte) (platform.ID, string, error) { + if len(key) < platform.IDLength { // This should not happen. - return influxdb.InvalidID(), "", errors.New("provided key is too short to contain an ID (please report this error)") + return platform.InvalidID(), "", errors.New("provided key is too short to contain an ID (please report this error)") } - var id influxdb.ID - if err := id.Decode(key[:influxdb.IDLength]); err != nil { - return influxdb.InvalidID(), "", err + var id platform.ID + if err := id.Decode(key[:platform.IDLength]); err != nil { + return platform.InvalidID(), "", err } - k := string(key[influxdb.IDLength:]) + k := string(key[platform.IDLength:]) return id, k, nil } diff --git a/session.go b/session.go index da71c84fe61..3c1434bc7df 100644 --- a/session.go +++ b/session.go @@ -3,6 +3,9 @@ package influxdb import ( "context" "time" + + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) // ErrSessionNotFound is the error messages for a missing sessions. @@ -34,19 +37,19 @@ const SessionAuthorizationKind = "session" // Session is a user session. type Session struct { // ID is only required for auditing purposes. - ID ID `json:"id"` + ID platform.ID `json:"id"` Key string `json:"key"` CreatedAt time.Time `json:"createdAt"` ExpiresAt time.Time `json:"expiresAt"` - UserID ID `json:"userID,omitempty"` + UserID platform.ID `json:"userID,omitempty"` Permissions []Permission `json:"permissions,omitempty"` } // Expired returns an error if the session is expired. func (s *Session) Expired() error { if time.Now().After(s.ExpiresAt) { - return &Error{ - Code: EForbidden, + return &errors.Error{ + Code: errors.EForbidden, Msg: ErrSessionExpired, } } @@ -57,8 +60,8 @@ func (s *Session) Expired() error { // PermissionSet returns the set of permissions associated with the session. func (s *Session) PermissionSet() (PermissionSet, error) { if err := s.Expired(); err != nil { - return nil, &Error{ - Code: EUnauthorized, + return nil, &errors.Error{ + Code: errors.EUnauthorized, Err: err, } } @@ -70,16 +73,16 @@ func (s *Session) PermissionSet() (PermissionSet, error) { func (s *Session) Kind() string { return SessionAuthorizationKind } // Identifier returns the sessions ID and is used for auditing. -func (s *Session) Identifier() ID { return s.ID } +func (s *Session) Identifier() platform.ID { return s.ID } // GetUserID returns the user id. -func (s *Session) GetUserID() ID { +func (s *Session) GetUserID() platform.ID { return s.UserID } // EphemeralAuth generates an Authorization that is not stored // but at the user's max privs. -func (s *Session) EphemeralAuth(orgID ID) *Authorization { +func (s *Session) EphemeralAuth(orgID platform.ID) *Authorization { return &Authorization{ ID: s.ID, OrgID: orgID, diff --git a/session/errors.go b/session/errors.go index 735a5f87d9f..b13557d16cd 100644 --- a/session/errors.go +++ b/session/errors.go @@ -1,14 +1,14 @@ package session import ( - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) var ( // ErrUnauthorized when a session request is unauthorized // usually due to password mismatch - ErrUnauthorized = &influxdb.Error{ - Code: influxdb.EUnauthorized, + ErrUnauthorized = &errors.Error{ + Code: errors.EUnauthorized, Msg: "unauthorized access", } ) diff --git a/session/http_server.go b/session/http_server.go index 6913eee7a3e..cae295d5f65 100644 --- a/session/http_server.go +++ b/session/http_server.go @@ -4,6 +4,8 @@ import ( "context" "net/http" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/influxdata/influxdb/v2" @@ -113,11 +115,11 @@ type signinRequest struct { Password string } -func decodeSigninRequest(ctx context.Context, r *http.Request) (*signinRequest, *influxdb.Error) { +func decodeSigninRequest(ctx context.Context, r *http.Request) (*signinRequest, *errors.Error) { u, p, ok := r.BasicAuth() if !ok { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "invalid basic auth", } } @@ -174,8 +176,8 @@ func encodeCookieSession(w http.ResponseWriter, s *influxdb.Session) { func decodeCookieSession(ctx context.Context, r *http.Request) (string, error) { c, err := r.Cookie(cookieSessionName) if err != nil { - return "", &influxdb.Error{ - Code: influxdb.EInvalid, + return "", &errors.Error{ + Code: errors.EInvalid, Err: err, } } diff --git a/session/http_server_test.go b/session/http_server_test.go index dbc9a4d549c..4f033805bde 100644 --- a/session/http_server_test.go +++ b/session/http_server_test.go @@ -7,6 +7,8 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" "go.uber.org/zap/zaptest" @@ -38,16 +40,16 @@ func TestSessionHandler_handleSignin(t *testing.T) { SessionService: &mock.SessionService{ CreateSessionFn: func(context.Context, string) (*influxdb.Session, error) { return &influxdb.Session{ - ID: influxdb.ID(0), + ID: platform.ID(0), Key: "abc123xyz", CreatedAt: time.Date(2018, 9, 26, 0, 0, 0, 0, time.UTC), ExpiresAt: time.Date(2030, 9, 26, 0, 0, 0, 0, time.UTC), - UserID: influxdb.ID(1), + UserID: platform.ID(1), }, nil }, }, PasswordsService: &mock.PasswordsService{ - ComparePasswordFn: func(context.Context, influxdb.ID, string) error { + ComparePasswordFn: func(context.Context, platform.ID, string) error { return nil }, }, diff --git a/session/service.go b/session/service.go index a24cef7e54a..afcaa63039e 100644 --- a/session/service.go +++ b/session/service.go @@ -4,6 +4,9 @@ import ( "context" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/rand" "github.com/influxdata/influxdb/v2/snowflake" @@ -18,7 +21,7 @@ type Service struct { authService influxdb.AuthorizationService sessionLength time.Duration - idGen influxdb.IDGenerator + idGen platform.IDGenerator tokenGen influxdb.TokenGenerator disableAuthorizationsForMaxPermissions func(context.Context) bool @@ -37,7 +40,7 @@ func WithSessionLength(length time.Duration) ServiceOption { // WithIDGenerator overrides the default ID generator with the one // provided to this function when called on a *Service -func WithIDGenerator(gen influxdb.IDGenerator) ServiceOption { +func WithIDGenerator(gen platform.IDGenerator) ServiceOption { return func(s *Service) { s.idGen = gen } @@ -139,14 +142,14 @@ func (s *Service) CreateSession(ctx context.Context, user string) (*influxdb.Ses // RenewSession update the sessions expiration time func (s *Service) RenewSession(ctx context.Context, session *influxdb.Session, newExpiration time.Time) error { if session == nil { - return &influxdb.Error{ + return &errors.Error{ Msg: "session is nil", } } return s.store.RefreshSession(ctx, session.ID, newExpiration) } -func (s *Service) getPermissionSet(ctx context.Context, uid influxdb.ID) ([]influxdb.Permission, error) { +func (s *Service) getPermissionSet(ctx context.Context, uid platform.ID) ([]influxdb.Permission, error) { mappings, _, err := s.urmService.FindUserResourceMappings(ctx, influxdb.UserResourceMappingFilter{UserID: uid}, influxdb.FindOptions{Limit: 100}) if err != nil { return nil, err @@ -192,7 +195,7 @@ func permissionFromMapping(mappings []*influxdb.UserResourceMapping) ([]influxdb for _, m := range mappings { p, err := m.ToPermissions() if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } diff --git a/session/storage.go b/session/storage.go index d933774a08a..b585f9ab2f5 100644 --- a/session/storage.go +++ b/session/storage.go @@ -5,6 +5,9 @@ import ( "encoding/json" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) @@ -37,13 +40,13 @@ func (s *Storage) FindSessionByKey(ctx context.Context, key string) (*influxdb.S } if val == "" { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrSessionNotFound, } } - id, err := influxdb.IDFromString(val) + id, err := platform.IDFromString(val) if err != nil { return nil, err } @@ -51,14 +54,14 @@ func (s *Storage) FindSessionByKey(ctx context.Context, key string) (*influxdb.S } // FindSessionByID use a provided id to retrieve the stored session -func (s *Storage) FindSessionByID(ctx context.Context, id influxdb.ID) (*influxdb.Session, error) { +func (s *Storage) FindSessionByID(ctx context.Context, id platform.ID) (*influxdb.Session, error) { val, err := s.store.Get(storePrefix + id.String()) if err != nil { return nil, err } if val == "" { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: influxdb.ErrSessionNotFound, } } @@ -91,7 +94,7 @@ func (s *Storage) CreateSession(ctx context.Context, session *influxdb.Session) } // RefreshSession updates the expiration time of a session. -func (s *Storage) RefreshSession(ctx context.Context, id influxdb.ID, expireAt time.Time) error { +func (s *Storage) RefreshSession(ctx context.Context, id platform.ID, expireAt time.Time) error { session, err := s.FindSessionByID(ctx, id) if err != nil { return err @@ -107,7 +110,7 @@ func (s *Storage) RefreshSession(ctx context.Context, id influxdb.ID, expireAt t } // DeleteSession removes the session and index from storage -func (s *Storage) DeleteSession(ctx context.Context, id influxdb.ID) error { +func (s *Storage) DeleteSession(ctx context.Context, id platform.ID) error { session, err := s.FindSessionByID(ctx, id) if err != nil { return err @@ -127,7 +130,7 @@ func (s *Storage) DeleteSession(ctx context.Context, id influxdb.ID) error { return nil } -func sessionID(id influxdb.ID) string { +func sessionID(id platform.ID) string { return storePrefix + id.String() } diff --git a/snowflake/id.go b/snowflake/id.go index 33d4a297f33..a3764b5d23b 100644 --- a/snowflake/id.go +++ b/snowflake/id.go @@ -6,7 +6,8 @@ import ( "sync" "time" - platform "github.com/influxdata/influxdb/v2" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/pkg/snowflake" ) @@ -85,10 +86,10 @@ func NewIDGenerator(opts ...IDGeneratorOp) *IDGenerator { } // ID returns the next platform.ID from an IDGenerator. -func (g *IDGenerator) ID() platform.ID { - var id platform.ID +func (g *IDGenerator) ID() platform2.ID { + var id platform2.ID for !id.Valid() { - id = platform.ID(g.Generator.Next()) + id = platform2.ID(g.Generator.Next()) } return id } diff --git a/snowflake/id_test.go b/snowflake/id_test.go index b53f2efd565..3498294681f 100644 --- a/snowflake/id_test.go +++ b/snowflake/id_test.go @@ -3,7 +3,7 @@ package snowflake import ( "testing" - platform "github.com/influxdata/influxdb/v2" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" ) func TestIDLength(t *testing.T) { @@ -13,7 +13,7 @@ func TestIDLength(t *testing.T) { t.Fail() } enc, _ := id.Encode() - if len(enc) != platform.IDLength { + if len(enc) != platform2.IDLength { t.Fail() } } @@ -21,7 +21,7 @@ func TestIDLength(t *testing.T) { func TestToFromString(t *testing.T) { gen := NewIDGenerator() id := gen.ID() - var clone platform.ID + var clone platform2.ID if err := clone.DecodeFromString(id.String()); err != nil { t.Error(err) } else if id != clone { diff --git a/source.go b/source.go index c62ded99cec..bcf4d92c4c1 100644 --- a/source.go +++ b/source.go @@ -1,6 +1,10 @@ package influxdb -import "context" +import ( + "context" + + "github.com/influxdata/influxdb/v2/kit/platform" +) const ( // ErrSourceNotFound is an error message when a source does not exist. @@ -23,14 +27,14 @@ const ( // TODO(desa): do we still need default? // TODO(desa): do sources belong type Source struct { - ID ID `json:"id,omitempty"` // ID is the unique ID of the source - OrganizationID ID `json:"orgID"` // OrganizationID is the organization ID that resource belongs to - Default bool `json:"default"` // Default specifies the default source for the application - Name string `json:"name"` // Name is the user-defined name for the source - Type SourceType `json:"type,omitempty"` // Type specifies which kinds of source (enterprise vs oss vs 2.0) - URL string `json:"url"` // URL are the connections to the source - InsecureSkipVerify bool `json:"insecureSkipVerify,omitempty"` // InsecureSkipVerify as true means any certificate presented by the source is accepted - Telegraf string `json:"telegraf"` // Telegraf is the db telegraf is written to. By default it is "telegraf" + ID platform.ID `json:"id,omitempty"` // ID is the unique ID of the source + OrganizationID platform.ID `json:"orgID"` // OrganizationID is the organization ID that resource belongs to + Default bool `json:"default"` // Default specifies the default source for the application + Name string `json:"name"` // Name is the user-defined name for the source + Type SourceType `json:"type,omitempty"` // Type specifies which kinds of source (enterprise vs oss vs 2.0) + URL string `json:"url"` // URL are the connections to the source + InsecureSkipVerify bool `json:"insecureSkipVerify,omitempty"` // InsecureSkipVerify as true means any certificate presented by the source is accepted + Telegraf string `json:"telegraf"` // Telegraf is the db telegraf is written to. By default it is "telegraf" SourceFields V1SourceFields } @@ -64,15 +68,15 @@ type SourceService interface { // DefaultSource retrieves the default source. DefaultSource(ctx context.Context) (*Source, error) // FindSourceByID retrieves a source by its ID. - FindSourceByID(ctx context.Context, id ID) (*Source, error) + FindSourceByID(ctx context.Context, id platform.ID) (*Source, error) // FindSources returns a list of all sources. FindSources(ctx context.Context, opts FindOptions) ([]*Source, int, error) // CreateSource sets the sources ID and stores it. CreateSource(ctx context.Context, s *Source) error // UpdateSource updates the source. - UpdateSource(ctx context.Context, id ID, upd SourceUpdate) (*Source, error) + UpdateSource(ctx context.Context, id platform.ID, upd SourceUpdate) (*Source, error) // DeleteSource removes the source. - DeleteSource(ctx context.Context, id ID) error + DeleteSource(ctx context.Context, id platform.ID) error } // DefaultSourceFindOptions are the default find options for sources diff --git a/status.go b/status.go index 45446a8679f..fc113acbd38 100644 --- a/status.go +++ b/status.go @@ -1,6 +1,10 @@ package influxdb -import "fmt" +import ( + "fmt" + + "github.com/influxdata/influxdb/v2/kit/platform/errors" +) // Status defines if a resource is active or inactive. type Status string @@ -18,8 +22,8 @@ func (s Status) Valid() error { case Active, Inactive: return nil default: - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("invalid status: must be %v or %v", Active, Inactive), } } diff --git a/storage/bucket_service.go b/storage/bucket_service.go index eb031500c03..4f2852b5058 100644 --- a/storage/bucket_service.go +++ b/storage/bucket_service.go @@ -3,6 +3,8 @@ package storage import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/tracing" "github.com/influxdata/influxdb/v2/v1/services/meta" @@ -11,8 +13,8 @@ import ( type EngineSchema interface { CreateBucket(context.Context, *influxdb.Bucket) error - UpdateBucketRetentionPolicy(context.Context, influxdb.ID, *influxdb.BucketUpdate) error - DeleteBucket(context.Context, influxdb.ID, influxdb.ID) error + UpdateBucketRetentionPolicy(context.Context, platform.ID, *influxdb.BucketUpdate) error + DeleteBucket(context.Context, platform.ID, platform.ID) error } // BucketService wraps an existing influxdb.BucketService implementation. @@ -66,7 +68,7 @@ func (s *BucketService) CreateBucket(ctx context.Context, b *influxdb.Bucket) (e return nil } -func (s *BucketService) UpdateBucket(ctx context.Context, id influxdb.ID, upd influxdb.BucketUpdate) (b *influxdb.Bucket, err error) { +func (s *BucketService) UpdateBucket(ctx context.Context, id platform.ID, upd influxdb.BucketUpdate) (b *influxdb.Bucket, err error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -78,7 +80,7 @@ func (s *BucketService) UpdateBucket(ctx context.Context, id influxdb.ID, upd in } // DeleteBucket removes a bucket by ID. -func (s *BucketService) DeleteBucket(ctx context.Context, bucketID influxdb.ID) error { +func (s *BucketService) DeleteBucket(ctx context.Context, bucketID platform.ID) error { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() diff --git a/storage/bucket_service_test.go b/storage/bucket_service_test.go index 9b07e5c8681..245bbe6f219 100644 --- a/storage/bucket_service_test.go +++ b/storage/bucket_service_test.go @@ -2,6 +2,7 @@ package storage_test import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" "testing" "time" @@ -119,7 +120,7 @@ func TestBucketService_DeleteNonexistentBucket(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - i, err := influxdb.IDFromString("2222222222222222") + i, err := platform.IDFromString("2222222222222222") require.NoError(t, err) engine := mocks.NewMockEngineSchema(ctrl) diff --git a/storage/engine.go b/storage/engine.go index 1f7d3858fdb..7b9e1bff7ea 100644 --- a/storage/engine.go +++ b/storage/engine.go @@ -8,6 +8,9 @@ import ( "sync" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/influxql/query" "github.com/influxdata/influxdb/v2/kit/tracing" @@ -242,7 +245,7 @@ func (e *Engine) Close() error { // Rosalie was here lockdown 2020 // // Appropriate errors are returned in those cases. -func (e *Engine) WritePoints(ctx context.Context, orgID influxdb.ID, bucketID influxdb.ID, points []models.Point) error { +func (e *Engine) WritePoints(ctx context.Context, orgID platform.ID, bucketID platform.ID, points []models.Point) error { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -275,7 +278,7 @@ func (e *Engine) CreateBucket(ctx context.Context, b *influxdb.Bucket) (err erro return nil } -func (e *Engine) UpdateBucketRetentionPolicy(ctx context.Context, bucketID influxdb.ID, upd *influxdb.BucketUpdate) error { +func (e *Engine) UpdateBucketRetentionPolicy(ctx context.Context, bucketID platform.ID, upd *influxdb.BucketUpdate) error { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -286,8 +289,8 @@ func (e *Engine) UpdateBucketRetentionPolicy(ctx context.Context, bucketID influ err := e.metaClient.UpdateRetentionPolicy(bucketID.String(), meta.DefaultRetentionPolicyName, &rpu, true) if err == meta.ErrIncompatibleDurations { - err = &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + err = &errors2.Error{ + Code: errors2.EUnprocessableEntity, Msg: "shard-group duration must also be updated to be smaller than new retention duration", } } @@ -295,7 +298,7 @@ func (e *Engine) UpdateBucketRetentionPolicy(ctx context.Context, bucketID influ } // DeleteBucket deletes an entire bucket from the storage engine. -func (e *Engine) DeleteBucket(ctx context.Context, orgID, bucketID influxdb.ID) error { +func (e *Engine) DeleteBucket(ctx context.Context, orgID, bucketID platform.ID) error { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() return e.tsdbStore.DeleteDatabase(bucketID.String()) @@ -303,7 +306,7 @@ func (e *Engine) DeleteBucket(ctx context.Context, orgID, bucketID influxdb.ID) // DeleteBucketRangePredicate deletes data within a bucket from the storage engine. Any data // deleted must be in [min, max], and the key must match the predicate if provided. -func (e *Engine) DeleteBucketRangePredicate(ctx context.Context, orgID, bucketID influxdb.ID, min, max int64, pred influxdb.Predicate) error { +func (e *Engine) DeleteBucketRangePredicate(ctx context.Context, orgID, bucketID platform.ID, min, max int64, pred influxdb.Predicate) error { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -382,7 +385,7 @@ func (e *Engine) RestoreKVStore(ctx context.Context, r io.Reader) error { return nil } -func (e *Engine) RestoreBucket(ctx context.Context, id influxdb.ID, buf []byte) (map[uint64]uint64, error) { +func (e *Engine) RestoreBucket(ctx context.Context, id platform.ID, buf []byte) (map[uint64]uint64, error) { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -460,7 +463,7 @@ func (e *Engine) RestoreShard(ctx context.Context, shardID uint64, r io.Reader) } // SeriesCardinality returns the number of series in the engine. -func (e *Engine) SeriesCardinality(orgID, bucketID influxdb.ID) int64 { +func (e *Engine) SeriesCardinality(orgID, bucketID platform.ID) int64 { e.mu.RLock() defer e.mu.RUnlock() if e.closing == nil { diff --git a/storage/flux/reader.go b/storage/flux/reader.go index 4ac3f726fcf..e02cabc304b 100644 --- a/storage/flux/reader.go +++ b/storage/flux/reader.go @@ -5,6 +5,8 @@ import ( "fmt" "strings" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/gogo/protobuf/types" "github.com/influxdata/flux" "github.com/influxdata/flux/execute" @@ -12,7 +14,6 @@ import ( "github.com/influxdata/flux/memory" "github.com/influxdata/flux/plan" "github.com/influxdata/flux/values" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/models" "github.com/influxdata/influxdb/v2/query" storage "github.com/influxdata/influxdb/v2/storage/reads" @@ -261,8 +262,8 @@ func (gi *groupIterator) Do(f func(flux.Table) error) error { req.Range.End = int64(gi.spec.Bounds.Stop) if len(gi.spec.GroupKeys) > 0 && gi.spec.GroupMode == query.GroupModeNone { - return &influxdb.Error{ - Code: influxdb.EInternal, + return &errors.Error{ + Code: errors.EInternal, Msg: "cannot have group mode none with group key values", } } diff --git a/storage/flux/table.gen.go b/storage/flux/table.gen.go index 7ce118638e4..76d0b984391 100644 --- a/storage/flux/table.gen.go +++ b/storage/flux/table.gen.go @@ -18,7 +18,7 @@ import ( "github.com/influxdata/flux/interval" "github.com/influxdata/flux/memory" "github.com/influxdata/flux/values" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "github.com/influxdata/influxdb/v2/models" storage "github.com/influxdata/influxdb/v2/storage/reads" "github.com/influxdata/influxdb/v2/storage/reads/datatypes" @@ -786,8 +786,8 @@ func determineFloatAggregateMethod(agg datatypes.Aggregate_AggregateType) (float return aggregateLastGroupsFloat, nil case datatypes.AggregateTypeCount: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unsupported for aggregate count: Float", } @@ -804,8 +804,8 @@ func determineFloatAggregateMethod(agg datatypes.Aggregate_AggregateType) (float return aggregateMaxGroupsFloat, nil default: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("unknown/unimplemented aggregate type: %v", agg), } } @@ -891,8 +891,8 @@ func (t *floatGroupTable) advanceCursor() bool { if typedCur, ok := cur.(cursors.FloatArrayCursor); !ok { // TODO(sgc): error or skip? cur.Close() - t.err = &influxdb.Error{ - Code: influxdb.EInvalid, + t.err = &errors.Error{ + Code: errors.EInvalid, Err: &GroupCursorError{ typ: "float", cursor: cur, @@ -1697,8 +1697,8 @@ func determineIntegerAggregateMethod(agg datatypes.Aggregate_AggregateType) (int return aggregateMaxGroupsInteger, nil default: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("unknown/unimplemented aggregate type: %v", agg), } } @@ -1788,8 +1788,8 @@ func (t *integerGroupTable) advanceCursor() bool { if typedCur, ok := cur.(cursors.IntegerArrayCursor); !ok { // TODO(sgc): error or skip? cur.Close() - t.err = &influxdb.Error{ - Code: influxdb.EInvalid, + t.err = &errors.Error{ + Code: errors.EInvalid, Err: &GroupCursorError{ typ: "integer", cursor: cur, @@ -2577,8 +2577,8 @@ func determineUnsignedAggregateMethod(agg datatypes.Aggregate_AggregateType) (un return aggregateLastGroupsUnsigned, nil case datatypes.AggregateTypeCount: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unsupported for aggregate count: Unsigned", } @@ -2595,8 +2595,8 @@ func determineUnsignedAggregateMethod(agg datatypes.Aggregate_AggregateType) (un return aggregateMaxGroupsUnsigned, nil default: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("unknown/unimplemented aggregate type: %v", agg), } } @@ -2682,8 +2682,8 @@ func (t *unsignedGroupTable) advanceCursor() bool { if typedCur, ok := cur.(cursors.UnsignedArrayCursor); !ok { // TODO(sgc): error or skip? cur.Close() - t.err = &influxdb.Error{ - Code: influxdb.EInvalid, + t.err = &errors.Error{ + Code: errors.EInvalid, Err: &GroupCursorError{ typ: "unsigned", cursor: cur, @@ -3471,35 +3471,35 @@ func determineStringAggregateMethod(agg datatypes.Aggregate_AggregateType) (stri return aggregateLastGroupsString, nil case datatypes.AggregateTypeCount: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unsupported for aggregate count: String", } case datatypes.AggregateTypeSum: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unsupported for aggregate sum: String", } case datatypes.AggregateTypeMin: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unsupported for aggregate min: String", } case datatypes.AggregateTypeMax: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unsupported for aggregate max: String", } default: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("unknown/unimplemented aggregate type: %v", agg), } } @@ -3549,8 +3549,8 @@ func (t *stringGroupTable) advanceCursor() bool { if typedCur, ok := cur.(cursors.StringArrayCursor); !ok { // TODO(sgc): error or skip? cur.Close() - t.err = &influxdb.Error{ - Code: influxdb.EInvalid, + t.err = &errors.Error{ + Code: errors.EInvalid, Err: &GroupCursorError{ typ: "string", cursor: cur, @@ -4338,35 +4338,35 @@ func determineBooleanAggregateMethod(agg datatypes.Aggregate_AggregateType) (boo return aggregateLastGroupsBoolean, nil case datatypes.AggregateTypeCount: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unsupported for aggregate count: Boolean", } case datatypes.AggregateTypeSum: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unsupported for aggregate sum: Boolean", } case datatypes.AggregateTypeMin: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unsupported for aggregate min: Boolean", } case datatypes.AggregateTypeMax: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unsupported for aggregate max: Boolean", } default: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("unknown/unimplemented aggregate type: %v", agg), } } @@ -4416,8 +4416,8 @@ func (t *booleanGroupTable) advanceCursor() bool { if typedCur, ok := cur.(cursors.BooleanArrayCursor); !ok { // TODO(sgc): error or skip? cur.Close() - t.err = &influxdb.Error{ - Code: influxdb.EInvalid, + t.err = &errors.Error{ + Code: errors.EInvalid, Err: &GroupCursorError{ typ: "boolean", cursor: cur, diff --git a/storage/flux/table.gen.go.tmpl b/storage/flux/table.gen.go.tmpl index f5180f88cd1..e6c168967c7 100644 --- a/storage/flux/table.gen.go.tmpl +++ b/storage/flux/table.gen.go.tmpl @@ -12,7 +12,7 @@ import ( "github.com/influxdata/flux/interval" "github.com/influxdata/flux/memory" "github.com/influxdata/flux/values" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "github.com/influxdata/influxdb/v2/models" "github.com/influxdata/influxdb/v2/storage/reads/datatypes" storage "github.com/influxdata/influxdb/v2/storage/reads" @@ -784,8 +784,8 @@ func determine{{.Name}}AggregateMethod(agg datatypes.Aggregate_AggregateType) ({ {{if eq .Name "Integer"}} return aggregateCountGroups{{.Name}}, nil {{else}} - return nil, &influxdb.Error { - Code: influxdb.EInvalid, + return nil, &errors.Error { + Code: errors.EInvalid, Msg: "unsupported for aggregate count: {{.Name}}", } {{end}} @@ -793,8 +793,8 @@ func determine{{.Name}}AggregateMethod(agg datatypes.Aggregate_AggregateType) ({ {{if and (ne .Name "Boolean") (ne .Name "String")}} return aggregateSumGroups{{.Name}}, nil {{else}} - return nil, &influxdb.Error { - Code: influxdb.EInvalid, + return nil, &errors.Error { + Code: errors.EInvalid, Msg: "unsupported for aggregate sum: {{.Name}}", } {{end}} @@ -802,8 +802,8 @@ func determine{{.Name}}AggregateMethod(agg datatypes.Aggregate_AggregateType) ({ {{if and (ne .Name "Boolean") (ne .Name "String")}} return aggregateMinGroups{{.Name}}, nil {{else}} - return nil, &influxdb.Error { - Code: influxdb.EInvalid, + return nil, &errors.Error { + Code: errors.EInvalid, Msg: "unsupported for aggregate min: {{.Name}}", } {{end}} @@ -811,14 +811,14 @@ func determine{{.Name}}AggregateMethod(agg datatypes.Aggregate_AggregateType) ({ {{if and (ne .Name "Boolean") (ne .Name "String")}} return aggregateMaxGroups{{.Name}}, nil {{else}} - return nil, &influxdb.Error { - Code: influxdb.EInvalid, + return nil, &errors.Error { + Code: errors.EInvalid, Msg: "unsupported for aggregate max: {{.Name}}", } {{end}} default: - return nil, &influxdb.Error { - Code: influxdb.EInvalid, + return nil, &errors.Error { + Code: errors.EInvalid, Msg: fmt.Sprintf("unknown/unimplemented aggregate type: %v", agg), } } @@ -915,8 +915,8 @@ func (t *{{.name}}GroupTable) advanceCursor() bool { if typedCur, ok := cur.(cursors.{{.Name}}ArrayCursor); !ok { // TODO(sgc): error or skip? cur.Close() - t.err = &influxdb.Error { - Code: influxdb.EInvalid, + t.err = &errors.Error { + Code: errors.EInvalid, Err: &GroupCursorError { typ: "{{.name}}", cursor: cur, diff --git a/storage/flux/window.go b/storage/flux/window.go index 3337656378f..b9b3675beef 100644 --- a/storage/flux/window.go +++ b/storage/flux/window.go @@ -5,13 +5,14 @@ import ( "fmt" "sync/atomic" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/apache/arrow/go/arrow/array" "github.com/apache/arrow/go/arrow/memory" "github.com/influxdata/flux" "github.com/influxdata/flux/arrow" "github.com/influxdata/flux/execute" "github.com/influxdata/flux/values" - "github.com/influxdata/influxdb/v2" ) // splitWindows will split a windowTable by creating a new table from each @@ -111,13 +112,13 @@ func (w *windowTableSplitter) Do(f func(flux.Table) error) error { func (w *windowTableSplitter) getTimeColumnIndex(label string) (int, error) { j := execute.ColIdx(label, w.in.Cols()) if j < 0 { - return -1, &influxdb.Error{ - Code: influxdb.EInvalid, + return -1, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("missing %q column from window splitter", label), } } else if c := w.in.Cols()[j]; c.Type != flux.TTime { - return -1, &influxdb.Error{ - Code: influxdb.EInvalid, + return -1, &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("%q column must be of type time", label), } } @@ -140,8 +141,8 @@ func (w *windowTableRow) Cols() []flux.ColMeta { func (w *windowTableRow) Do(f func(flux.ColReader) error) error { if !atomic.CompareAndSwapInt32(&w.used, 0, 1) { - return &influxdb.Error{ - Code: influxdb.EInternal, + return &errors.Error{ + Code: errors.EInternal, Msg: "table already read", } } diff --git a/storage/mocks/EngineSchema.go b/storage/mocks/EngineSchema.go index 2aad9252bac..d242166d8e9 100644 --- a/storage/mocks/EngineSchema.go +++ b/storage/mocks/EngineSchema.go @@ -6,6 +6,7 @@ package mocks import ( context "context" + "github.com/influxdata/influxdb/v2/kit/platform" reflect "reflect" gomock "github.com/golang/mock/gomock" @@ -50,7 +51,7 @@ func (mr *MockEngineSchemaMockRecorder) CreateBucket(arg0, arg1 interface{}) *go } // DeleteBucket mocks base method. -func (m *MockEngineSchema) DeleteBucket(arg0 context.Context, arg1, arg2 influxdb.ID) error { +func (m *MockEngineSchema) DeleteBucket(arg0 context.Context, arg1, arg2 platform.ID) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteBucket", arg0, arg1, arg2) ret0, _ := ret[0].(error) @@ -64,7 +65,7 @@ func (mr *MockEngineSchemaMockRecorder) DeleteBucket(arg0, arg1, arg2 interface{ } // UpdateBucketRetentionPolicy mocks base method. -func (m *MockEngineSchema) UpdateBucketRetentionPolicy(arg0 context.Context, arg1 influxdb.ID, arg2 *influxdb.BucketUpdate) error { +func (m *MockEngineSchema) UpdateBucketRetentionPolicy(arg0 context.Context, arg1 platform.ID, arg2 *influxdb.BucketUpdate) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "UpdateBucketRetentionPolicy", arg0, arg1, arg2) ret0, _ := ret[0].(error) diff --git a/storage/points_writer.go b/storage/points_writer.go index fa4c1810343..85e30bb015e 100644 --- a/storage/points_writer.go +++ b/storage/points_writer.go @@ -5,13 +5,15 @@ import ( "fmt" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/models" ) // PointsWriter describes the ability to write points into a storage engine. type PointsWriter interface { - WritePoints(ctx context.Context, orgID influxdb.ID, bucketID influxdb.ID, points []models.Point) error + WritePoints(ctx context.Context, orgID platform.ID, bucketID platform.ID, points []models.Point) error } // LoggingPointsWriter wraps an underlying points writer but writes logs to @@ -28,7 +30,7 @@ type LoggingPointsWriter struct { } // WritePoints writes points to the underlying PointsWriter. Logs on error. -func (w *LoggingPointsWriter) WritePoints(ctx context.Context, orgID influxdb.ID, bucketID influxdb.ID, p []models.Point) error { +func (w *LoggingPointsWriter) WritePoints(ctx context.Context, orgID platform.ID, bucketID platform.ID, p []models.Point) error { if len(p) == 0 { return nil } @@ -69,14 +71,14 @@ func (w *LoggingPointsWriter) WritePoints(ctx context.Context, orgID influxdb.ID type BufferedPointsWriter struct { buf []models.Point - orgID influxdb.ID - bucketID influxdb.ID + orgID platform.ID + bucketID platform.ID n int wr PointsWriter err error } -func NewBufferedPointsWriter(orgID influxdb.ID, bucketID influxdb.ID, size int, pointswriter PointsWriter) *BufferedPointsWriter { +func NewBufferedPointsWriter(orgID platform.ID, bucketID platform.ID, size int, pointswriter PointsWriter) *BufferedPointsWriter { return &BufferedPointsWriter{ buf: make([]models.Point, size), orgID: orgID, diff --git a/storage/reads/array_cursor.gen.go b/storage/reads/array_cursor.gen.go index 2a00e7af010..5ad1efeb655 100644 --- a/storage/reads/array_cursor.gen.go +++ b/storage/reads/array_cursor.gen.go @@ -13,7 +13,7 @@ import ( "github.com/influxdata/flux/interval" "github.com/influxdata/flux/values" - "github.com/influxdata/influxdb/v2" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" "github.com/influxdata/influxdb/v2/tsdb/cursors" ) @@ -135,8 +135,8 @@ func newWindowSumArrayCursor(cur cursors.Cursor, window interval.Window) (cursor return newUnsignedWindowSumArrayCursor(cur, window), nil default: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: fmt.Sprintf("unsupported input type for sum aggregate: %s", arrayCursorType(cur)), } } @@ -189,8 +189,8 @@ func newWindowMeanArrayCursor(cur cursors.Cursor, window interval.Window) (curso return newUnsignedWindowMeanArrayCursor(cur, window), nil default: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: fmt.Sprintf("unsupported input type for mean aggregate: %s", arrayCursorType(cur)), } } diff --git a/storage/reads/array_cursor.gen.go.tmpl b/storage/reads/array_cursor.gen.go.tmpl index 5e1e7aa25e7..a1c3f27888a 100644 --- a/storage/reads/array_cursor.gen.go.tmpl +++ b/storage/reads/array_cursor.gen.go.tmpl @@ -7,7 +7,7 @@ import ( "github.com/influxdata/flux/interval" "github.com/influxdata/flux/values" - "github.com/influxdata/influxdb/v2" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" "github.com/influxdata/influxdb/v2/tsdb/cursors" ) @@ -80,8 +80,8 @@ func newWindowSumArrayCursor(cur cursors.Cursor, window interval.Window) (cursor {{end}}{{/* for each supported agg fn */}} {{end}}{{/* for each field type */}} default: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: fmt.Sprintf("unsupported input type for sum aggregate: %s", arrayCursorType(cur)), } } @@ -131,8 +131,8 @@ func newWindowMeanArrayCursor(cur cursors.Cursor, window interval.Window) (curso {{end}}{{/* for each supported agg fn */}} {{end}}{{/* for each field type */}} default: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors2.Error{ + Code: errors2.EInvalid, Msg: fmt.Sprintf("unsupported input type for mean aggregate: %s", arrayCursorType(cur)), } } diff --git a/tag.go b/tag.go index 43879ac66a0..371c0482c61 100644 --- a/tag.go +++ b/tag.go @@ -4,6 +4,8 @@ import ( "encoding/json" "regexp" "strings" + + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) // Operator is an Enum value of operators. @@ -12,8 +14,8 @@ type Operator int // Valid returns invalid error if the operator is invalid. func (op Operator) Valid() error { if op < Equal || op > NotRegexEqual { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "Operator is invalid", } } @@ -68,15 +70,15 @@ func (op Operator) MarshalJSON() ([]byte, error) { func (op *Operator) UnmarshalJSON(b []byte) error { var s string if err := json.Unmarshal(b, &s); err != nil { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Err: err, } } var ok bool if *op, ok = opStrMap[s]; !ok { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "unrecognized operator", } } @@ -95,8 +97,8 @@ func NewTag(s string) (Tag, error) { matched, err := regexp.MatchString(`^[a-zA-Z0-9_]+:[a-zA-Z0-9_]+$`, s) if !matched || err != nil { - return tagPair, &Error{ - Code: EInvalid, + return tagPair, &errors.Error{ + Code: errors.EInvalid, Msg: `tag must be in form key:value`, } } @@ -111,8 +113,8 @@ func NewTag(s string) (Tag, error) { // Valid returns an error if the tagpair is missing fields func (t Tag) Valid() error { if t.Key == "" || t.Value == "" { - return &Error{ - Code: EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "tag must contain a key and a value", } } diff --git a/tag_test.go b/tag_test.go index a23917fdd1c..40f1e33cce6 100644 --- a/tag_test.go +++ b/tag_test.go @@ -1,6 +1,7 @@ package influxdb_test import ( + "github.com/influxdata/influxdb/v2/kit/platform/errors" "testing" "github.com/influxdata/influxdb/v2" @@ -23,8 +24,8 @@ func TestTagValid(t *testing.T) { { name: "empty", src: influxdb.TagRule{}, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "tag must contain a key and a value", }, }, @@ -33,8 +34,8 @@ func TestTagValid(t *testing.T) { src: influxdb.TagRule{ Tag: influxdb.Tag{Value: "v1"}, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "tag must contain a key and a value", }, }, @@ -43,8 +44,8 @@ func TestTagValid(t *testing.T) { src: influxdb.TagRule{ Tag: influxdb.Tag{Key: "k1"}, }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "tag must contain a key and a value", }, }, @@ -54,8 +55,8 @@ func TestTagValid(t *testing.T) { Tag: influxdb.Tag{Key: "k1", Value: "v1"}, Operator: influxdb.Operator(-1), }, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "Operator is invalid", }, }, diff --git a/task.go b/task.go index 0314a37cf58..78c01978ca7 100644 --- a/task.go +++ b/task.go @@ -8,6 +8,9 @@ import ( "strconv" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/flux/ast" "github.com/influxdata/flux/ast/edit" "github.com/influxdata/influxdb/v2/task/options" @@ -30,11 +33,11 @@ var ( // Task is a task. 🎊 type Task struct { - ID ID `json:"id"` + ID platform.ID `json:"id"` Type string `json:"type,omitempty"` - OrganizationID ID `json:"orgID"` + OrganizationID platform.ID `json:"orgID"` Organization string `json:"org"` - OwnerID ID `json:"ownerID"` + OwnerID platform.ID `json:"ownerID"` Name string `json:"name"` Description string `json:"description,omitempty"` Status string `json:"status"` @@ -70,22 +73,22 @@ func (t *Task) EffectiveCron() string { // Run is a record createId when a run of a task is scheduled. type Run struct { - ID ID `json:"id,omitempty"` - TaskID ID `json:"taskID"` - Status string `json:"status"` - ScheduledFor time.Time `json:"scheduledFor"` // ScheduledFor is the Now time used in the task's query - RunAt time.Time `json:"runAt"` // RunAt is the time the task is scheduled to be run, which is ScheduledFor + Offset - StartedAt time.Time `json:"startedAt,omitempty"` // StartedAt is the time the executor begins running the task - FinishedAt time.Time `json:"finishedAt,omitempty"` // FinishedAt is the time the executor finishes running the task - RequestedAt time.Time `json:"requestedAt,omitempty"` // RequestedAt is the time the coordinator told the scheduler to schedule the task - Log []Log `json:"log,omitempty"` + ID platform.ID `json:"id,omitempty"` + TaskID platform.ID `json:"taskID"` + Status string `json:"status"` + ScheduledFor time.Time `json:"scheduledFor"` // ScheduledFor is the Now time used in the task's query + RunAt time.Time `json:"runAt"` // RunAt is the time the task is scheduled to be run, which is ScheduledFor + Offset + StartedAt time.Time `json:"startedAt,omitempty"` // StartedAt is the time the executor begins running the task + FinishedAt time.Time `json:"finishedAt,omitempty"` // FinishedAt is the time the executor finishes running the task + RequestedAt time.Time `json:"requestedAt,omitempty"` // RequestedAt is the time the coordinator told the scheduler to schedule the task + Log []Log `json:"log,omitempty"` } // Log represents a link to a log resource type Log struct { - RunID ID `json:"runID,omitempty"` - Time string `json:"time"` - Message string `json:"message"` + RunID platform.ID `json:"runID,omitempty"` + Time string `json:"time"` + Message string `json:"message"` } func (l Log) String() string { @@ -95,7 +98,7 @@ func (l Log) String() string { // TaskService represents a service for managing one-off and recurring tasks. type TaskService interface { // FindTaskByID returns a single task - FindTaskByID(ctx context.Context, id ID) (*Task, error) + FindTaskByID(ctx context.Context, id platform.ID) (*Task, error) // FindTasks returns a list of tasks that match a filter (limit 100) and the total count // of matching tasks. @@ -106,10 +109,10 @@ type TaskService interface { CreateTask(ctx context.Context, t TaskCreate) (*Task, error) // UpdateTask updates a single task with changeset. - UpdateTask(ctx context.Context, id ID, upd TaskUpdate) (*Task, error) + UpdateTask(ctx context.Context, id platform.ID, upd TaskUpdate) (*Task, error) // DeleteTask removes a task by ID and purges all associated data and scheduled runs. - DeleteTask(ctx context.Context, id ID) error + DeleteTask(ctx context.Context, id platform.ID) error // FindLogs returns logs for a run. FindLogs(ctx context.Context, filter LogFilter) ([]*Log, int, error) @@ -118,17 +121,17 @@ type TaskService interface { FindRuns(ctx context.Context, filter RunFilter) ([]*Run, int, error) // FindRunByID returns a single run. - FindRunByID(ctx context.Context, taskID, runID ID) (*Run, error) + FindRunByID(ctx context.Context, taskID, runID platform.ID) (*Run, error) // CancelRun cancels a currently running run. - CancelRun(ctx context.Context, taskID, runID ID) error + CancelRun(ctx context.Context, taskID, runID platform.ID) error // RetryRun creates and returns a new run (which is a retry of another run). - RetryRun(ctx context.Context, taskID, runID ID) (*Run, error) + RetryRun(ctx context.Context, taskID, runID platform.ID) (*Run, error) // ForceRun forces a run to occur with unix timestamp scheduledFor, to be executed as soon as possible. // The value of scheduledFor may or may not align with the task's schedule. - ForceRun(ctx context.Context, taskID ID, scheduledFor int64) (*Run, error) + ForceRun(ctx context.Context, taskID platform.ID, scheduledFor int64) (*Run, error) } // TaskCreate is the set of values to create a task. @@ -137,9 +140,9 @@ type TaskCreate struct { Flux string `json:"flux"` Description string `json:"description,omitempty"` Status string `json:"status,omitempty"` - OrganizationID ID `json:"orgID,omitempty"` + OrganizationID platform.ID `json:"orgID,omitempty"` Organization string `json:"org,omitempty"` - OwnerID ID `json:"-"` + OwnerID platform.ID `json:"-"` Metadata map[string]interface{} `json:"-"` // not to be set through a web request but rather used by a http service using tasks backend. } @@ -275,15 +278,15 @@ func (t *TaskUpdate) Validate() error { // and is guaranteed not to panic. func safeParseSource(parser FluxLanguageService, f string) (pkg *ast.Package, err error) { if parser == nil { - return nil, &Error{ - Code: EInternal, + return nil, &errors2.Error{ + Code: errors2.EInternal, Msg: "flux parser is not configured; updating a task requires the flux parser to be set", } } defer func() { if r := recover(); r != nil { - err = &Error{ - Code: EInternal, + err = &errors2.Error{ + Code: errors2.EInternal, Msg: "internal error in flux engine; unable to parse", } } @@ -408,10 +411,10 @@ func (t *TaskUpdate) updateFlux(parser FluxLanguageService, oldFlux string) erro type TaskFilter struct { Type *string Name *string - After *ID - OrganizationID *ID + After *platform.ID + OrganizationID *platform.ID Organization string - User *ID + User *platform.ID Limit int Status *string } @@ -445,9 +448,9 @@ func (f TaskFilter) QueryParams() map[string][]string { // RunFilter represents a set of filters that restrict the returned results type RunFilter struct { // Task ID is required for listing runs. - Task ID + Task platform.ID - After *ID + After *platform.ID Limit int AfterTime string BeforeTime string @@ -456,10 +459,10 @@ type RunFilter struct { // LogFilter represents a set of filters that restrict the returned log results. type LogFilter struct { // Task ID is required. - Task ID + Task platform.ID // The optional Run ID limits logs to a single run. - Run *ID + Run *platform.ID } type TaskStatus string diff --git a/task/backend/analytical_storage.go b/task/backend/analytical_storage.go index 7f5442b40bc..1daed2b6550 100644 --- a/task/backend/analytical_storage.go +++ b/task/backend/analytical_storage.go @@ -7,6 +7,9 @@ import ( "fmt" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/flux" "github.com/influxdata/flux/lang" "github.com/influxdata/influxdb/v2" @@ -31,7 +34,7 @@ const ( // RunRecorder is a type which records runs into an influxdb // backed storage mechanism type RunRecorder interface { - Record(ctx context.Context, orgID influxdb.ID, org string, bucketID influxdb.ID, bucket string, run *influxdb.Run) error + Record(ctx context.Context, orgID platform.ID, org string, bucketID platform.ID, bucket string, run *influxdb.Run) error } // NewAnalyticalRunStorage creates a new analytical store with access to the necessary systems for storing data and to act as a middleware @@ -68,7 +71,7 @@ type AnalyticalStorage struct { log *zap.Logger } -func (as *AnalyticalStorage) FinishRun(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (as *AnalyticalStorage) FinishRun(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { run, err := as.TaskControlService.FinishRun(ctx, taskID, runID) if run != nil && run.ID.String() != "" { task, err := as.TaskService.FindTaskByID(ctx, run.TaskID) @@ -240,7 +243,7 @@ func (as *AnalyticalStorage) FindRuns(ctx context.Context, filter influxdb.RunFi // remove any kv runs that exist in the list of completed runs func (as *AnalyticalStorage) combineRuns(currentRuns, completeRuns []*influxdb.Run) []*influxdb.Run { - crMap := map[influxdb.ID]int{} + crMap := map[platform.ID]int{} // track the current runs for i, cr := range currentRuns { @@ -260,11 +263,11 @@ func (as *AnalyticalStorage) combineRuns(currentRuns, completeRuns []*influxdb.R // FindRunByID returns a single run. // First see if it is in the existing TaskService. If not pull it from analytical storage. -func (as *AnalyticalStorage) FindRunByID(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (as *AnalyticalStorage) FindRunByID(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { // check the taskService to see if the run is on its list run, err := as.TaskService.FindRunByID(ctx, taskID, runID) if err != nil { - if err, ok := err.(*influxdb.Error); !ok || err.Msg != "run not found" { + if err, ok := err.(*errors2.Error); !ok || err.Msg != "run not found" { return run, err } } @@ -336,19 +339,19 @@ func (as *AnalyticalStorage) FindRunByID(ctx context.Context, taskID, runID infl } if len(re.runs) != 1 { - return nil, &influxdb.Error{ + return nil, &errors2.Error{ Msg: "found multiple runs with id " + runID.String(), - Code: influxdb.EInternal, + Code: errors2.EInternal, } } return re.runs[0], err } -func (as *AnalyticalStorage) RetryRun(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (as *AnalyticalStorage) RetryRun(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { run, err := as.TaskService.RetryRun(ctx, taskID, runID) if err != nil { - if err, ok := err.(*influxdb.Error); !ok || err.Msg != "run not found" { + if err, ok := err.(*errors2.Error); !ok || err.Msg != "run not found" { return run, err } } @@ -384,7 +387,7 @@ func (re *runReader) readRuns(cr flux.ColReader) error { switch col.Label { case runIDField: if cr.Strings(j).ValueString(i) != "" { - id, err := influxdb.IDFromString(cr.Strings(j).ValueString(i)) + id, err := platform.IDFromString(cr.Strings(j).ValueString(i)) if err != nil { re.log.Info("Failed to parse runID", zap.Error(err)) continue @@ -393,7 +396,7 @@ func (re *runReader) readRuns(cr flux.ColReader) error { } case taskIDTag: if cr.Strings(j).ValueString(i) != "" { - id, err := influxdb.IDFromString(cr.Strings(j).ValueString(i)) + id, err := platform.IDFromString(cr.Strings(j).ValueString(i)) if err != nil { re.log.Info("Failed to parse taskID", zap.Error(err)) continue diff --git a/task/backend/analytical_storage_test.go b/task/backend/analytical_storage_test.go index f63431bf6a3..e3011c98c80 100644 --- a/task/backend/analytical_storage_test.go +++ b/task/backend/analytical_storage_test.go @@ -2,6 +2,7 @@ package backend_test import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" "io/ioutil" "os" "testing" @@ -103,14 +104,14 @@ func TestDeduplicateRuns(t *testing.T) { metaClient := meta.NewClient(meta.NewConfig(), store) require.NoError(t, metaClient.Open()) - _, err := metaClient.CreateDatabase(influxdb.ID(10).String()) + _, err := metaClient.CreateDatabase(platform.ID(10).String()) require.NoError(t, err) ab := newAnalyticalBackend(t, ts.OrganizationService, ts.BucketService, metaClient) defer ab.Close(t) mockTS := &mock.TaskService{ - FindTaskByIDFn: func(context.Context, influxdb.ID) (*influxdb.Task, error) { + FindTaskByIDFn: func(context.Context, platform.ID) (*influxdb.Task, error) { return &influxdb.Task{ID: 1, OrganizationID: 20}, nil }, FindRunsFn: func(context.Context, influxdb.RunFilter) ([]*influxdb.Run, int, error) { @@ -120,7 +121,7 @@ func TestDeduplicateRuns(t *testing.T) { }, } mockTCS := &mock.TaskControlService{ - FinishRunFn: func(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { + FinishRunFn: func(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { return &influxdb.Run{ID: 2, TaskID: 1, Status: "success", ScheduledFor: time.Now(), StartedAt: time.Now().Add(1), FinishedAt: time.Now().Add(2)}, nil }, } diff --git a/task/backend/coordinator.go b/task/backend/coordinator.go index 231e1861ec3..bacc520e528 100644 --- a/task/backend/coordinator.go +++ b/task/backend/coordinator.go @@ -4,6 +4,8 @@ import ( "context" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "go.uber.org/zap" ) @@ -15,7 +17,7 @@ var now = func() time.Time { // TaskService is a type on which tasks can be listed type TaskService interface { FindTasks(context.Context, influxdb.TaskFilter) ([]*influxdb.Task, int, error) - UpdateTask(context.Context, influxdb.ID, influxdb.TaskUpdate) (*influxdb.Task, error) + UpdateTask(context.Context, platform.ID, influxdb.TaskUpdate) (*influxdb.Task, error) } // Coordinator is a type with a single method which @@ -63,7 +65,7 @@ func NotifyCoordinatorOfExisting(ctx context.Context, log *zap.Logger, ts TaskSe return nil } -type TaskResumer func(ctx context.Context, id influxdb.ID, runID influxdb.ID) error +type TaskResumer func(ctx context.Context, id platform.ID, runID platform.ID) error // TaskNotifyCoordinatorOfExisting lists all tasks by the provided task service and for // each task it calls the provided coordinators task created method diff --git a/task/backend/coordinator/coordinator.go b/task/backend/coordinator/coordinator.go index b76cf3ce886..2d6de259302 100644 --- a/task/backend/coordinator/coordinator.go +++ b/task/backend/coordinator/coordinator.go @@ -5,6 +5,8 @@ import ( "errors" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/task/backend/executor" "github.com/influxdata/influxdb/v2/task/backend/middleware" @@ -20,8 +22,8 @@ const DefaultLimit = 1000 // Executor is an abstraction of the task executor with only the functions needed by the coordinator type Executor interface { - ManualRun(ctx context.Context, id influxdb.ID, runID influxdb.ID) (executor.Promise, error) - Cancel(ctx context.Context, runID influxdb.ID) error + ManualRun(ctx context.Context, id platform.ID, runID platform.ID) (executor.Promise, error) + Cancel(ctx context.Context, runID platform.ID) error } // Coordinator is the intermediary between the scheduling/executing system and the rest of the task system @@ -144,7 +146,7 @@ func (c *Coordinator) TaskUpdated(ctx context.Context, from, to *influxdb.Task) } //TaskDeleted asks the Scheduler to release the deleted task -func (c *Coordinator) TaskDeleted(ctx context.Context, id influxdb.ID) error { +func (c *Coordinator) TaskDeleted(ctx context.Context, id platform.ID) error { tid := scheduler.ID(id) if err := c.sch.Release(tid); err != nil && err != influxdb.ErrTaskNotClaimed { return err @@ -154,7 +156,7 @@ func (c *Coordinator) TaskDeleted(ctx context.Context, id influxdb.ID) error { } // RunCancelled speaks directly to the executor to cancel a task run -func (c *Coordinator) RunCancelled(ctx context.Context, runID influxdb.ID) error { +func (c *Coordinator) RunCancelled(ctx context.Context, runID platform.ID) error { err := c.ex.Cancel(ctx, runID) return err diff --git a/task/backend/coordinator/coordinator_test.go b/task/backend/coordinator/coordinator_test.go index 40f03a566ad..05f2292ccf8 100644 --- a/task/backend/coordinator/coordinator_test.go +++ b/task/backend/coordinator/coordinator_test.go @@ -6,6 +6,8 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/influxdata/influxdb/v2" @@ -15,7 +17,7 @@ import ( func Test_Coordinator_Executor_Methods(t *testing.T) { var ( - one = influxdb.ID(1) + one = platform.ID(1) taskOne = &influxdb.Task{ID: one} runOne = &influxdb.Run{ @@ -96,7 +98,7 @@ func Test_Coordinator_Executor_Methods(t *testing.T) { func TestNewSchedulableTask(t *testing.T) { now := time.Now().UTC() - one := influxdb.ID(1) + one := platform.ID(1) taskOne := &influxdb.Task{ID: one, CreatedAt: now, Cron: "* * * * *", LatestCompleted: now} schedulableT, err := NewSchedulableTask(taskOne) if err != nil { @@ -121,9 +123,9 @@ func TestNewSchedulableTask(t *testing.T) { func Test_Coordinator_Scheduler_Methods(t *testing.T) { var ( - one = influxdb.ID(1) - two = influxdb.ID(2) - three = influxdb.ID(3) + one = platform.ID(1) + two = platform.ID(2) + three = platform.ID(3) now = time.Now().UTC() taskOne = &influxdb.Task{ID: one, CreatedAt: now, Cron: "* * * * *"} diff --git a/task/backend/coordinator/support_test.go b/task/backend/coordinator/support_test.go index 6bbab72cdbe..0154cef16b6 100644 --- a/task/backend/coordinator/support_test.go +++ b/task/backend/coordinator/support_test.go @@ -3,6 +3,8 @@ package coordinator import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/task/backend/executor" "github.com/influxdata/influxdb/v2/task/backend/scheduler" @@ -16,12 +18,12 @@ type ( } manualRunCall struct { - TaskID influxdb.ID - RunID influxdb.ID + TaskID platform.ID + RunID platform.ID } cancelCallC struct { - RunID influxdb.ID + RunID platform.ID } ) @@ -54,7 +56,7 @@ type ( ) // ID is the id of the run that was created -func (p *promise) ID() influxdb.ID { +func (p *promise) ID() platform.ID { return p.run.ID } @@ -94,7 +96,7 @@ func (s *schedulerC) Release(taskID scheduler.ID) error { return nil } -func (e *executorE) ManualRun(ctx context.Context, id influxdb.ID, runID influxdb.ID) (executor.Promise, error) { +func (e *executorE) ManualRun(ctx context.Context, id platform.ID, runID platform.ID) (executor.Promise, error) { e.calls = append(e.calls, manualRunCall{id, runID}) ctx, cancel := context.WithCancel(ctx) p := promise{ @@ -108,7 +110,7 @@ func (e *executorE) ManualRun(ctx context.Context, id influxdb.ID, runID influxd return &p, err } -func (e *executorE) Cancel(ctx context.Context, runID influxdb.ID) error { +func (e *executorE) Cancel(ctx context.Context, runID platform.ID) error { e.calls = append(e.calls, cancelCallC{runID}) return nil } diff --git a/task/backend/coordinator_test.go b/task/backend/coordinator_test.go index 8172efbf11f..49afc2f506c 100644 --- a/task/backend/coordinator_test.go +++ b/task/backend/coordinator_test.go @@ -5,16 +5,18 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" "go.uber.org/zap/zaptest" ) var ( - one = influxdb.ID(1) - two = influxdb.ID(2) - three = influxdb.ID(3) - four = influxdb.ID(4) + one = platform.ID(1) + two = platform.ID(2) + three = platform.ID(3) + four = platform.ID(4) aTime = time.Now().UTC() @@ -23,7 +25,7 @@ var ( taskThree = &influxdb.Task{ID: three, Status: "inactive"} taskFour = &influxdb.Task{ID: four} - allTasks = map[influxdb.ID]*influxdb.Task{ + allTasks = map[platform.ID]*influxdb.Task{ one: taskOne, two: taskTwo, three: taskThree, @@ -37,7 +39,7 @@ func Test_NotifyCoordinatorOfCreated(t *testing.T) { tasks = &taskService{ // paginated responses pageOne: []*influxdb.Task{taskOne}, - otherPages: map[influxdb.ID][]*influxdb.Task{ + otherPages: map[platform.ID][]*influxdb.Task{ one: {taskTwo, taskThree}, three: {taskFour}, }, @@ -81,7 +83,7 @@ func (c *coordinator) TaskCreated(_ context.Context, task *influxdb.Task) error type taskService struct { // paginated tasks pageOne []*influxdb.Task - otherPages map[influxdb.ID][]*influxdb.Task + otherPages map[platform.ID][]*influxdb.Task // find tasks call filter influxdb.TaskFilter @@ -90,11 +92,11 @@ type taskService struct { } type update struct { - ID influxdb.ID + ID platform.ID Update influxdb.TaskUpdate } -func (t *taskService) UpdateTask(_ context.Context, id influxdb.ID, upd influxdb.TaskUpdate) (*influxdb.Task, error) { +func (t *taskService) UpdateTask(_ context.Context, id platform.ID, upd influxdb.TaskUpdate) (*influxdb.Task, error) { t.updates = append(t.updates, update{id, upd}) return allTasks[id], nil diff --git a/task/backend/executor/executor.go b/task/backend/executor/executor.go index cab28016da9..abdf8650276 100644 --- a/task/backend/executor/executor.go +++ b/task/backend/executor/executor.go @@ -7,6 +7,8 @@ import ( "sync" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/flux" "github.com/influxdata/flux/ast" "github.com/influxdata/flux/lang" @@ -31,11 +33,11 @@ const ( var _ scheduler.Executor = (*Executor)(nil) type PermissionService interface { - FindPermissionForUser(ctx context.Context, UserID influxdb.ID) (influxdb.PermissionSet, error) + FindPermissionForUser(ctx context.Context, UserID platform.ID) (influxdb.PermissionSet, error) } type Promise interface { - ID() influxdb.ID + ID() platform.ID Cancel(ctx context.Context) Done() <-chan struct{} Error() error @@ -206,7 +208,7 @@ func (e *Executor) Execute(ctx context.Context, id scheduler.ID, scheduledFor ti // If the queue is full the call to execute should hang and apply back pressure to the caller // We then start a worker to work the newly queued jobs. func (e *Executor) PromisedExecute(ctx context.Context, id scheduler.ID, scheduledFor time.Time, runAt time.Time) (Promise, error) { - iid := influxdb.ID(id) + iid := platform.ID(id) // create a run p, err := e.createRun(ctx, iid, scheduledFor, runAt) if err != nil { @@ -217,7 +219,7 @@ func (e *Executor) PromisedExecute(ctx context.Context, id scheduler.ID, schedul return p, nil } -func (e *Executor) ManualRun(ctx context.Context, id influxdb.ID, runID influxdb.ID) (Promise, error) { +func (e *Executor) ManualRun(ctx context.Context, id platform.ID, runID platform.ID) (Promise, error) { // create promises for any manual runs r, err := e.tcs.StartManualRun(ctx, id, runID) if err != nil { @@ -230,7 +232,7 @@ func (e *Executor) ManualRun(ctx context.Context, id influxdb.ID, runID influxdb return p, err } -func (e *Executor) ResumeCurrentRun(ctx context.Context, id influxdb.ID, runID influxdb.ID) (Promise, error) { +func (e *Executor) ResumeCurrentRun(ctx context.Context, id platform.ID, runID platform.ID) (Promise, error) { cr, err := e.tcs.CurrentlyRunning(ctx, id) if err != nil { return nil, err @@ -252,7 +254,7 @@ func (e *Executor) ResumeCurrentRun(ctx context.Context, id influxdb.ID, runID i return nil, influxdb.ErrRunNotFound } -func (e *Executor) createRun(ctx context.Context, id influxdb.ID, scheduledFor time.Time, runAt time.Time) (*promise, error) { +func (e *Executor) createRun(ctx context.Context, id platform.ID, scheduledFor time.Time, runAt time.Time) (*promise, error) { r, err := e.tcs.CreateRun(ctx, id, scheduledFor.UTC(), runAt.UTC()) if err != nil { return nil, err @@ -297,7 +299,7 @@ func (e *Executor) startWorker() { } // Cancel a run of a specific task. -func (e *Executor) Cancel(ctx context.Context, runID influxdb.ID) error { +func (e *Executor) Cancel(ctx context.Context, runID platform.ID) error { // find the promise val, ok := e.currentPromises.Load(runID) if !ok { @@ -333,7 +335,7 @@ func (e *Executor) createPromise(ctx context.Context, run *influxdb.Run) (*promi auth: &influxdb.Authorization{ Status: influxdb.Active, UserID: t.OwnerID, - ID: influxdb.ID(1), + ID: platform.ID(1), OrgID: t.OrganizationID, Permissions: perm, }, @@ -583,7 +585,7 @@ type promise struct { } // ID is the id of the run that was created -func (p *promise) ID() influxdb.ID { +func (p *promise) ID() platform.ID { return p.run.ID } diff --git a/task/backend/executor/executor_metrics.go b/task/backend/executor/executor_metrics.go index f12c451de2d..c3d9b4a54b8 100644 --- a/task/backend/executor/executor_metrics.go +++ b/task/backend/executor/executor_metrics.go @@ -3,6 +3,9 @@ package executor import ( "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/prometheus/client_golang/prometheus" ) @@ -153,7 +156,7 @@ func (em *ExecutorMetrics) FinishRun(task *influxdb.Task, status influxdb.RunSta // LogError increments the count of errors by error code. func (em *ExecutorMetrics) LogError(taskType string, err error) { switch e := err.(type) { - case *influxdb.Error: + case *errors.Error: em.errorsCounter.WithLabelValues(taskType, e.Code).Inc() default: em.errorsCounter.WithLabelValues(taskType, "unknown").Inc() @@ -163,9 +166,9 @@ func (em *ExecutorMetrics) LogError(taskType string, err error) { // LogUnrecoverableError increments the count of unrecoverable errors, which require admin intervention to resolve or deactivate // This count is separate from the errors count so that the errors metric can be used to identify only internal, rather than user errors // and so that unrecoverable errors can be quickly identified for deactivation -func (em *ExecutorMetrics) LogUnrecoverableError(taskID influxdb.ID, err error) { +func (em *ExecutorMetrics) LogUnrecoverableError(taskID platform.ID, err error) { switch e := err.(type) { - case *influxdb.Error: + case *errors.Error: em.unrecoverableCounter.WithLabelValues(taskID.String(), e.Code).Inc() default: em.unrecoverableCounter.WithLabelValues(taskID.String(), "unknown").Inc() diff --git a/task/backend/executor/executor_test.go b/task/backend/executor/executor_test.go index 4826b96ca75..e4eddb0723b 100644 --- a/task/backend/executor/executor_test.go +++ b/task/backend/executor/executor_test.go @@ -10,6 +10,8 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/golang/mock/gomock" "github.com/influxdata/flux" "github.com/influxdata/influxdb/v2" @@ -130,7 +132,7 @@ func testQuerySuccess(t *testing.T) { if err != nil { t.Fatal(err) } - promiseID := influxdb.ID(promise.ID()) + promiseID := platform.ID(promise.ID()) run, err := tes.i.FindRunByID(context.Background(), task.ID, promiseID) if err != nil { @@ -192,7 +194,7 @@ func testQueryFailure(t *testing.T) { if err != nil { t.Fatal(err) } - promiseID := influxdb.ID(promise.ID()) + promiseID := platform.ID(promise.ID()) run, err := tes.i.FindRunByID(context.Background(), task.ID, promiseID) if err != nil { @@ -470,7 +472,7 @@ func testIteratorFailure(t *testing.T) { if err != nil { t.Fatal(err) } - promiseID := influxdb.ID(promise.ID()) + promiseID := platform.ID(promise.ID()) run, err := tes.i.FindRunByID(context.Background(), task.ID, promiseID) if err != nil { @@ -588,7 +590,7 @@ type taskControlService struct { run *influxdb.Run } -func (t *taskControlService) FinishRun(ctx context.Context, taskID influxdb.ID, runID influxdb.ID) (*influxdb.Run, error) { +func (t *taskControlService) FinishRun(ctx context.Context, taskID platform.ID, runID platform.ID) (*influxdb.Run, error) { // ensure auth set on context _, err := icontext.GetAuthorizer(ctx) if err != nil { diff --git a/task/backend/executor/mock/permission_service.go b/task/backend/executor/mock/permission_service.go index 91f79ddca2e..812fe70491e 100644 --- a/task/backend/executor/mock/permission_service.go +++ b/task/backend/executor/mock/permission_service.go @@ -8,6 +8,7 @@ import ( context "context" gomock "github.com/golang/mock/gomock" influxdb "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" reflect "reflect" ) @@ -35,7 +36,7 @@ func (m *MockPermissionService) EXPECT() *MockPermissionServiceMockRecorder { } // FindPermissionForUser mocks base method -func (m *MockPermissionService) FindPermissionForUser(ctx context.Context, UserID influxdb.ID) (influxdb.PermissionSet, error) { +func (m *MockPermissionService) FindPermissionForUser(ctx context.Context, UserID platform.ID) (influxdb.PermissionSet, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "FindPermissionForUser", ctx, UserID) ret0, _ := ret[0].(influxdb.PermissionSet) @@ -73,10 +74,10 @@ func (m *MockPromise) EXPECT() *MockPromiseMockRecorder { } // ID mocks base method -func (m *MockPromise) ID() influxdb.ID { +func (m *MockPromise) ID() platform.ID { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ID") - ret0, _ := ret[0].(influxdb.ID) + ret0, _ := ret[0].(platform.ID) return ret0 } diff --git a/task/backend/executor/support_test.go b/task/backend/executor/support_test.go index 8b197e13253..98be9f21a0e 100644 --- a/task/backend/executor/support_test.go +++ b/task/backend/executor/support_test.go @@ -8,6 +8,8 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/flux" "github.com/influxdata/flux/execute" "github.com/influxdata/flux/lang" @@ -250,7 +252,7 @@ func (ts tables) Do(f func(flux.Table) error) error { func (ts tables) Statistics() flux.Statistics { return flux.Statistics{} } type testCreds struct { - OrgID, UserID influxdb.ID + OrgID, UserID platform.ID Auth *influxdb.Authorization } diff --git a/task/backend/middleware/check_middleware.go b/task/backend/middleware/check_middleware.go index 58f9e04b28d..4a4097512ed 100644 --- a/task/backend/middleware/check_middleware.go +++ b/task/backend/middleware/check_middleware.go @@ -5,6 +5,8 @@ import ( "fmt" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -32,7 +34,7 @@ func NewCheckService(cs influxdb.CheckService, ts influxdb.TaskService, coordina } // CreateCheck Creates a check and Publishes the change it can be scheduled. -func (cs *CoordinatingCheckService) CreateCheck(ctx context.Context, c influxdb.CheckCreate, userID influxdb.ID) error { +func (cs *CoordinatingCheckService) CreateCheck(ctx context.Context, c influxdb.CheckCreate, userID platform.ID) error { if err := cs.CheckService.CreateCheck(ctx, c, userID); err != nil { return err @@ -55,7 +57,7 @@ func (cs *CoordinatingCheckService) CreateCheck(ctx context.Context, c influxdb. } // UpdateCheck Updates a check and publishes the change so the task owner can act on the update -func (cs *CoordinatingCheckService) UpdateCheck(ctx context.Context, id influxdb.ID, c influxdb.CheckCreate) (influxdb.Check, error) { +func (cs *CoordinatingCheckService) UpdateCheck(ctx context.Context, id platform.ID, c influxdb.CheckCreate) (influxdb.Check, error) { from, err := cs.CheckService.FindCheckByID(ctx, id) if err != nil { return nil, err @@ -86,7 +88,7 @@ func (cs *CoordinatingCheckService) UpdateCheck(ctx context.Context, id influxdb } // PatchCheck Updates a check and publishes the change so the task owner can act on the update -func (cs *CoordinatingCheckService) PatchCheck(ctx context.Context, id influxdb.ID, upd influxdb.CheckUpdate) (influxdb.Check, error) { +func (cs *CoordinatingCheckService) PatchCheck(ctx context.Context, id platform.ID, upd influxdb.CheckUpdate) (influxdb.Check, error) { from, err := cs.CheckService.FindCheckByID(ctx, id) if err != nil { return nil, err @@ -118,7 +120,7 @@ func (cs *CoordinatingCheckService) PatchCheck(ctx context.Context, id influxdb. } // DeleteCheck delete the check and publishes the change, to allow the task owner to find out about this change faster. -func (cs *CoordinatingCheckService) DeleteCheck(ctx context.Context, id influxdb.ID) error { +func (cs *CoordinatingCheckService) DeleteCheck(ctx context.Context, id platform.ID) error { check, err := cs.CheckService.FindCheckByID(ctx, id) if err != nil { return err diff --git a/task/backend/middleware/check_middleware_test.go b/task/backend/middleware/check_middleware_test.go index d3815cd6e42..030110d936f 100644 --- a/task/backend/middleware/check_middleware_test.go +++ b/task/backend/middleware/check_middleware_test.go @@ -3,6 +3,7 @@ package middleware_test import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" "testing" "time" @@ -17,7 +18,7 @@ type pipingCoordinator struct { err error taskCreatedPipe chan *influxdb.Task taskUpdatedPipe chan *influxdb.Task - taskDeletedPipe chan influxdb.ID + taskDeletedPipe chan platform.ID } func (p *pipingCoordinator) taskCreatedChan() <-chan *influxdb.Task { @@ -32,9 +33,9 @@ func (p *pipingCoordinator) taskUpdatedChan() <-chan *influxdb.Task { } return p.taskUpdatedPipe } -func (p *pipingCoordinator) taskDeletedChan() <-chan influxdb.ID { +func (p *pipingCoordinator) taskDeletedChan() <-chan platform.ID { if p.taskDeletedPipe == nil { - p.taskDeletedPipe = make(chan influxdb.ID, 1) + p.taskDeletedPipe = make(chan platform.ID, 1) } return p.taskDeletedPipe } @@ -51,13 +52,13 @@ func (p *pipingCoordinator) TaskUpdated(_ context.Context, from, to *influxdb.Ta } return p.err } -func (p *pipingCoordinator) TaskDeleted(_ context.Context, id influxdb.ID) error { +func (p *pipingCoordinator) TaskDeleted(_ context.Context, id platform.ID) error { if p.taskDeletedPipe != nil { p.taskDeletedPipe <- id } return p.err } -func (p *pipingCoordinator) RunCancelled(ctx context.Context, runID influxdb.ID) error { +func (p *pipingCoordinator) RunCancelled(ctx context.Context, runID platform.ID) error { return p.err } func (p *pipingCoordinator) RunRetried(ctx context.Context, task *influxdb.Task, run *influxdb.Run) error { @@ -77,44 +78,44 @@ type mockedSvc struct { func newMockServices() mockedSvc { return mockedSvc{ taskSvc: &mock.TaskService{ - FindTaskByIDFn: func(_ context.Context, id influxdb.ID) (*influxdb.Task, error) { return &influxdb.Task{ID: id}, nil }, + FindTaskByIDFn: func(_ context.Context, id platform.ID) (*influxdb.Task, error) { return &influxdb.Task{ID: id}, nil }, CreateTaskFn: func(context.Context, influxdb.TaskCreate) (*influxdb.Task, error) { return &influxdb.Task{ID: 1}, nil }, - UpdateTaskFn: func(_ context.Context, id influxdb.ID, _ influxdb.TaskUpdate) (*influxdb.Task, error) { + UpdateTaskFn: func(_ context.Context, id platform.ID, _ influxdb.TaskUpdate) (*influxdb.Task, error) { return &influxdb.Task{ID: id}, nil }, - DeleteTaskFn: func(context.Context, influxdb.ID) error { return nil }, + DeleteTaskFn: func(context.Context, platform.ID) error { return nil }, }, checkSvc: &mock.CheckService{ - FindCheckByIDFn: func(_ context.Context, id influxdb.ID) (influxdb.Check, error) { + FindCheckByIDFn: func(_ context.Context, id platform.ID) (influxdb.Check, error) { c := &check.Deadman{} c.SetID(id) return c, nil }, - CreateCheckFn: func(context.Context, influxdb.CheckCreate, influxdb.ID) error { return nil }, - UpdateCheckFn: func(_ context.Context, _ influxdb.ID, c influxdb.CheckCreate) (influxdb.Check, error) { return c, nil }, - PatchCheckFn: func(_ context.Context, id influxdb.ID, _ influxdb.CheckUpdate) (influxdb.Check, error) { + CreateCheckFn: func(context.Context, influxdb.CheckCreate, platform.ID) error { return nil }, + UpdateCheckFn: func(_ context.Context, _ platform.ID, c influxdb.CheckCreate) (influxdb.Check, error) { return c, nil }, + PatchCheckFn: func(_ context.Context, id platform.ID, _ influxdb.CheckUpdate) (influxdb.Check, error) { c := &check.Deadman{} c.SetID(id) return c, nil }, - DeleteCheckFn: func(context.Context, influxdb.ID) error { return nil }, + DeleteCheckFn: func(context.Context, platform.ID) error { return nil }, }, notificationSvc: &mock.NotificationRuleStore{ - FindNotificationRuleByIDF: func(_ context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { + FindNotificationRuleByIDF: func(_ context.Context, id platform.ID) (influxdb.NotificationRule, error) { c := &rule.HTTP{} c.SetID(id) return c, nil }, - CreateNotificationRuleF: func(context.Context, influxdb.NotificationRuleCreate, influxdb.ID) error { return nil }, - UpdateNotificationRuleF: func(_ context.Context, _ influxdb.ID, c influxdb.NotificationRuleCreate, _ influxdb.ID) (influxdb.NotificationRule, error) { + CreateNotificationRuleF: func(context.Context, influxdb.NotificationRuleCreate, platform.ID) error { return nil }, + UpdateNotificationRuleF: func(_ context.Context, _ platform.ID, c influxdb.NotificationRuleCreate, _ platform.ID) (influxdb.NotificationRule, error) { return c, nil }, - PatchNotificationRuleF: func(_ context.Context, id influxdb.ID, _ influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { + PatchNotificationRuleF: func(_ context.Context, id platform.ID, _ influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { c := &rule.HTTP{} c.SetID(id) return c, nil }, - DeleteNotificationRuleF: func(context.Context, influxdb.ID) error { return nil }, + DeleteNotificationRuleF: func(context.Context, platform.ID) error { return nil }, }, pipingCoordinator: &pipingCoordinator{}, } @@ -152,7 +153,7 @@ func TestCheckCreate(t *testing.T) { } mocks.pipingCoordinator.err = fmt.Errorf("bad") - mocks.checkSvc.DeleteCheckFn = func(context.Context, influxdb.ID) error { return fmt.Errorf("AARGH") } + mocks.checkSvc.DeleteCheckFn = func(context.Context, platform.ID) error { return fmt.Errorf("AARGH") } err = checkService.CreateCheck(context.Background(), cc, 1) if err.Error() != "schedule task failed: bad\n\tcleanup also failed: AARGH" { @@ -168,27 +169,27 @@ func TestCheckUpdateFromInactive(t *testing.T) { } ch := mocks.pipingCoordinator.taskUpdatedChan() - mocks.checkSvc.UpdateCheckFn = func(_ context.Context, _ influxdb.ID, c influxdb.CheckCreate) (influxdb.Check, error) { + mocks.checkSvc.UpdateCheckFn = func(_ context.Context, _ platform.ID, c influxdb.CheckCreate) (influxdb.Check, error) { c.SetTaskID(10) c.SetUpdatedAt(latest.Add(-20 * time.Hour)) return c, nil } - mocks.checkSvc.PatchCheckFn = func(_ context.Context, _ influxdb.ID, c influxdb.CheckUpdate) (influxdb.Check, error) { + mocks.checkSvc.PatchCheckFn = func(_ context.Context, _ platform.ID, c influxdb.CheckUpdate) (influxdb.Check, error) { ic := &check.Deadman{} ic.SetTaskID(10) ic.SetUpdatedAt(latest.Add(-20 * time.Hour)) return ic, nil } - mocks.checkSvc.FindCheckByIDFn = func(_ context.Context, id influxdb.ID) (influxdb.Check, error) { + mocks.checkSvc.FindCheckByIDFn = func(_ context.Context, id platform.ID) (influxdb.Check, error) { c := &check.Deadman{} c.SetID(id) c.SetTaskID(1) return c, nil } - mocks.taskSvc.FindTaskByIDFn = func(_ context.Context, id influxdb.ID) (*influxdb.Task, error) { + mocks.taskSvc.FindTaskByIDFn = func(_ context.Context, id platform.ID) (*influxdb.Task, error) { if id == 1 { return &influxdb.Task{ID: id, Status: string(influxdb.TaskInactive)}, nil } else if id == 10 { @@ -244,7 +245,7 @@ func TestCheckUpdate(t *testing.T) { mocks, checkService := newCheckSvcStack() ch := mocks.pipingCoordinator.taskUpdatedChan() - mocks.checkSvc.UpdateCheckFn = func(_ context.Context, _ influxdb.ID, c influxdb.CheckCreate) (influxdb.Check, error) { + mocks.checkSvc.UpdateCheckFn = func(_ context.Context, _ platform.ID, c influxdb.CheckCreate) (influxdb.Check, error) { c.SetTaskID(10) return c, nil } @@ -279,7 +280,7 @@ func TestCheckPatch(t *testing.T) { deadman := &check.Deadman{} deadman.SetTaskID(4) - mocks.checkSvc.PatchCheckFn = func(context.Context, influxdb.ID, influxdb.CheckUpdate) (influxdb.Check, error) { + mocks.checkSvc.PatchCheckFn = func(context.Context, platform.ID, influxdb.CheckUpdate) (influxdb.Check, error) { return deadman, nil } @@ -302,7 +303,7 @@ func TestCheckDelete(t *testing.T) { mocks, checkService := newCheckSvcStack() ch := mocks.pipingCoordinator.taskDeletedChan() - mocks.checkSvc.FindCheckByIDFn = func(_ context.Context, id influxdb.ID) (influxdb.Check, error) { + mocks.checkSvc.FindCheckByIDFn = func(_ context.Context, id platform.ID) (influxdb.Check, error) { c := &check.Deadman{} c.SetID(id) c.SetTaskID(21) @@ -316,7 +317,7 @@ func TestCheckDelete(t *testing.T) { select { case id := <-ch: - if id != influxdb.ID(21) { + if id != platform.ID(21) { t.Fatalf("task sent to coordinator doesn't match expected") } default: diff --git a/task/backend/middleware/middleware.go b/task/backend/middleware/middleware.go index 9c95e45ea92..6ddb7d28f8b 100644 --- a/task/backend/middleware/middleware.go +++ b/task/backend/middleware/middleware.go @@ -5,6 +5,8 @@ import ( "fmt" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -13,8 +15,8 @@ import ( type Coordinator interface { TaskCreated(context.Context, *influxdb.Task) error TaskUpdated(ctx context.Context, from, to *influxdb.Task) error - TaskDeleted(context.Context, influxdb.ID) error - RunCancelled(ctx context.Context, runID influxdb.ID) error + TaskDeleted(context.Context, platform.ID) error + RunCancelled(ctx context.Context, runID platform.ID) error RunRetried(ctx context.Context, task *influxdb.Task, run *influxdb.Run) error RunForced(ctx context.Context, task *influxdb.Task, run *influxdb.Run) error } @@ -64,7 +66,7 @@ func (s *CoordinatingTaskService) CreateTask(ctx context.Context, tc influxdb.Ta } // UpdateTask Updates a task and publishes the change so the task owner can act on the update -func (s *CoordinatingTaskService) UpdateTask(ctx context.Context, id influxdb.ID, upd influxdb.TaskUpdate) (*influxdb.Task, error) { +func (s *CoordinatingTaskService) UpdateTask(ctx context.Context, id platform.ID, upd influxdb.TaskUpdate) (*influxdb.Task, error) { from, err := s.TaskService.FindTaskByID(ctx, id) if err != nil { return nil, err @@ -79,7 +81,7 @@ func (s *CoordinatingTaskService) UpdateTask(ctx context.Context, id influxdb.ID } // DeleteTask delete the task and publishes the change, to allow the task owner to find out about this change faster. -func (s *CoordinatingTaskService) DeleteTask(ctx context.Context, id influxdb.ID) error { +func (s *CoordinatingTaskService) DeleteTask(ctx context.Context, id platform.ID) error { if err := s.coordinator.TaskDeleted(ctx, id); err != nil { return err } @@ -88,7 +90,7 @@ func (s *CoordinatingTaskService) DeleteTask(ctx context.Context, id influxdb.ID } // CancelRun Cancel the run and publish the cancellation. -func (s *CoordinatingTaskService) CancelRun(ctx context.Context, taskID, runID influxdb.ID) error { +func (s *CoordinatingTaskService) CancelRun(ctx context.Context, taskID, runID platform.ID) error { if err := s.TaskService.CancelRun(ctx, taskID, runID); err != nil { return err } @@ -97,7 +99,7 @@ func (s *CoordinatingTaskService) CancelRun(ctx context.Context, taskID, runID i } // RetryRun calls retry on the task service and publishes the retry. -func (s *CoordinatingTaskService) RetryRun(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (s *CoordinatingTaskService) RetryRun(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { t, err := s.TaskService.FindTaskByID(ctx, taskID) if err != nil { return nil, err @@ -112,7 +114,7 @@ func (s *CoordinatingTaskService) RetryRun(ctx context.Context, taskID, runID in } // ForceRun create the forced run in the task system and publish to the pubSub. -func (s *CoordinatingTaskService) ForceRun(ctx context.Context, taskID influxdb.ID, scheduledFor int64) (*influxdb.Run, error) { +func (s *CoordinatingTaskService) ForceRun(ctx context.Context, taskID platform.ID, scheduledFor int64) (*influxdb.Run, error) { t, err := s.TaskService.FindTaskByID(ctx, taskID) if err != nil { return nil, err diff --git a/task/backend/middleware/middleware_test.go b/task/backend/middleware/middleware_test.go index 5388fa2f0dd..77d6fdb1f39 100644 --- a/task/backend/middleware/middleware_test.go +++ b/task/backend/middleware/middleware_test.go @@ -3,13 +3,14 @@ package middleware_test import ( "context" "errors" + "github.com/influxdata/influxdb/v2/kit/platform" "sync" "testing" "time" "github.com/influxdata/influxdb/v2" - pmock "github.com/influxdata/influxdb/v2/mock" _ "github.com/influxdata/influxdb/v2/fluxinit/static" + pmock "github.com/influxdata/influxdb/v2/mock" "github.com/influxdata/influxdb/v2/snowflake" "github.com/influxdata/influxdb/v2/task/backend" "github.com/influxdata/influxdb/v2/task/backend/coordinator" @@ -32,7 +33,7 @@ const script = `option task = {name: "a task",cron: "* * * * *"} from(bucket:"te func inmemTaskService() influxdb.TaskService { gen := snowflake.NewDefaultIDGenerator() - tasks := map[influxdb.ID]*influxdb.Task{} + tasks := map[platform.ID]*influxdb.Task{} mu := sync.Mutex{} ts := &pmock.TaskService{ @@ -48,13 +49,13 @@ func inmemTaskService() influxdb.TaskService { return tasks[id], nil }, - DeleteTaskFn: func(ctx context.Context, id influxdb.ID) error { + DeleteTaskFn: func(ctx context.Context, id platform.ID) error { mu.Lock() defer mu.Unlock() delete(tasks, id) return nil }, - UpdateTaskFn: func(ctx context.Context, id influxdb.ID, upd influxdb.TaskUpdate) (*influxdb.Task, error) { + UpdateTaskFn: func(ctx context.Context, id platform.ID, upd influxdb.TaskUpdate) (*influxdb.Task, error) { mu.Lock() defer mu.Unlock() t, ok := tasks[id] @@ -74,7 +75,7 @@ func inmemTaskService() influxdb.TaskService { return t, nil }, - FindTaskByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Task, error) { + FindTaskByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Task, error) { mu.Lock() defer mu.Unlock() t, ok := tasks[id] @@ -96,7 +97,7 @@ func inmemTaskService() influxdb.TaskService { } return rtn, len(rtn), nil }, - ForceRunFn: func(ctx context.Context, id influxdb.ID, scheduledFor int64) (*influxdb.Run, error) { + ForceRunFn: func(ctx context.Context, id platform.ID, scheduledFor int64) (*influxdb.Run, error) { mu.Lock() defer mu.Unlock() t, ok := tasks[id] @@ -220,7 +221,7 @@ func TestCoordinatingTaskService_ForceRun(t *testing.T) { t.Fatal(err) } - if influxdb.ID(id) != task.ID { + if platform.ID(id) != task.ID { t.Fatalf("expected task ID passed to scheduler to match create task ID %v, got: %v", task.ID, id) } diff --git a/task/backend/middleware/notification_middleware.go b/task/backend/middleware/notification_middleware.go index 0d9974be1cf..176c3b1bb4c 100644 --- a/task/backend/middleware/notification_middleware.go +++ b/task/backend/middleware/notification_middleware.go @@ -5,6 +5,8 @@ import ( "fmt" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -32,7 +34,7 @@ func NewNotificationRuleStore(ns influxdb.NotificationRuleStore, ts influxdb.Tas } // CreateNotificationRule Creates a notification and Publishes the change it can be scheduled. -func (ns *CoordinatingNotificationRuleStore) CreateNotificationRule(ctx context.Context, nr influxdb.NotificationRuleCreate, userID influxdb.ID) error { +func (ns *CoordinatingNotificationRuleStore) CreateNotificationRule(ctx context.Context, nr influxdb.NotificationRuleCreate, userID platform.ID) error { if err := ns.NotificationRuleStore.CreateNotificationRule(ctx, nr, userID); err != nil { return err @@ -55,7 +57,7 @@ func (ns *CoordinatingNotificationRuleStore) CreateNotificationRule(ctx context. } // UpdateNotificationRule Updates a notification and publishes the change so the task owner can act on the update -func (ns *CoordinatingNotificationRuleStore) UpdateNotificationRule(ctx context.Context, id influxdb.ID, nr influxdb.NotificationRuleCreate, uid influxdb.ID) (influxdb.NotificationRule, error) { +func (ns *CoordinatingNotificationRuleStore) UpdateNotificationRule(ctx context.Context, id platform.ID, nr influxdb.NotificationRuleCreate, uid platform.ID) (influxdb.NotificationRule, error) { from, err := ns.NotificationRuleStore.FindNotificationRuleByID(ctx, id) if err != nil { return nil, err @@ -85,7 +87,7 @@ func (ns *CoordinatingNotificationRuleStore) UpdateNotificationRule(ctx context. } // PatchNotificationRule Updates a notification and publishes the change so the task owner can act on the update -func (ns *CoordinatingNotificationRuleStore) PatchNotificationRule(ctx context.Context, id influxdb.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { +func (ns *CoordinatingNotificationRuleStore) PatchNotificationRule(ctx context.Context, id platform.ID, upd influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { from, err := ns.NotificationRuleStore.FindNotificationRuleByID(ctx, id) if err != nil { return nil, err @@ -117,7 +119,7 @@ func (ns *CoordinatingNotificationRuleStore) PatchNotificationRule(ctx context.C } // DeleteNotificationRule delete the notification and publishes the change, to allow the task owner to find out about this change faster. -func (ns *CoordinatingNotificationRuleStore) DeleteNotificationRule(ctx context.Context, id influxdb.ID) error { +func (ns *CoordinatingNotificationRuleStore) DeleteNotificationRule(ctx context.Context, id platform.ID) error { notification, err := ns.NotificationRuleStore.FindNotificationRuleByID(ctx, id) if err != nil { return err diff --git a/task/backend/middleware/notification_middleware_test.go b/task/backend/middleware/notification_middleware_test.go index f1f8e78a505..26379218275 100644 --- a/task/backend/middleware/notification_middleware_test.go +++ b/task/backend/middleware/notification_middleware_test.go @@ -3,6 +3,7 @@ package middleware_test import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" "testing" "time" @@ -43,7 +44,7 @@ func TestNotificationRuleCreate(t *testing.T) { } mocks.pipingCoordinator.err = fmt.Errorf("bad") - mocks.notificationSvc.DeleteNotificationRuleF = func(context.Context, influxdb.ID) error { return fmt.Errorf("AARGH") } + mocks.notificationSvc.DeleteNotificationRuleF = func(context.Context, platform.ID) error { return fmt.Errorf("AARGH") } err = nrService.CreateNotificationRule(context.Background(), nrc, 1) if err.Error() != "schedule task failed: bad\n\tcleanup also failed: AARGH" { @@ -59,27 +60,27 @@ func TestNotificationRuleUpdateFromInactive(t *testing.T) { } ch := mocks.pipingCoordinator.taskUpdatedChan() - mocks.notificationSvc.UpdateNotificationRuleF = func(_ context.Context, _ influxdb.ID, c influxdb.NotificationRuleCreate, _ influxdb.ID) (influxdb.NotificationRule, error) { + mocks.notificationSvc.UpdateNotificationRuleF = func(_ context.Context, _ platform.ID, c influxdb.NotificationRuleCreate, _ platform.ID) (influxdb.NotificationRule, error) { c.SetTaskID(10) c.SetUpdatedAt(latest.Add(-20 * time.Hour)) return c, nil } - mocks.notificationSvc.PatchNotificationRuleF = func(_ context.Context, id influxdb.ID, _ influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { + mocks.notificationSvc.PatchNotificationRuleF = func(_ context.Context, id platform.ID, _ influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { ic := &rule.HTTP{} ic.SetTaskID(10) ic.SetUpdatedAt(latest.Add(-20 * time.Hour)) return ic, nil } - mocks.notificationSvc.FindNotificationRuleByIDF = func(_ context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { + mocks.notificationSvc.FindNotificationRuleByIDF = func(_ context.Context, id platform.ID) (influxdb.NotificationRule, error) { c := &rule.HTTP{} c.SetID(id) c.SetTaskID(1) return c, nil } - mocks.taskSvc.FindTaskByIDFn = func(_ context.Context, id influxdb.ID) (*influxdb.Task, error) { + mocks.taskSvc.FindTaskByIDFn = func(_ context.Context, id platform.ID) (*influxdb.Task, error) { if id == 1 { return &influxdb.Task{ID: id, Status: string(influxdb.TaskInactive)}, nil } else if id == 10 { @@ -134,7 +135,7 @@ func TestNotificationRuleUpdate(t *testing.T) { mocks, nrService := newNotificationRuleSvcStack() ch := mocks.pipingCoordinator.taskUpdatedChan() - mocks.notificationSvc.UpdateNotificationRuleF = func(_ context.Context, _ influxdb.ID, c influxdb.NotificationRuleCreate, _ influxdb.ID) (influxdb.NotificationRule, error) { + mocks.notificationSvc.UpdateNotificationRuleF = func(_ context.Context, _ platform.ID, c influxdb.NotificationRuleCreate, _ platform.ID) (influxdb.NotificationRule, error) { c.SetTaskID(10) return c, nil } @@ -169,7 +170,7 @@ func TestNotificationRulePatch(t *testing.T) { deadman := &rule.HTTP{} deadman.SetTaskID(4) - mocks.notificationSvc.PatchNotificationRuleF = func(context.Context, influxdb.ID, influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { + mocks.notificationSvc.PatchNotificationRuleF = func(context.Context, platform.ID, influxdb.NotificationRuleUpdate) (influxdb.NotificationRule, error) { return deadman, nil } @@ -192,7 +193,7 @@ func TestNotificationRuleDelete(t *testing.T) { mocks, nrService := newNotificationRuleSvcStack() ch := mocks.pipingCoordinator.taskDeletedChan() - mocks.notificationSvc.FindNotificationRuleByIDF = func(_ context.Context, id influxdb.ID) (influxdb.NotificationRule, error) { + mocks.notificationSvc.FindNotificationRuleByIDF = func(_ context.Context, id platform.ID) (influxdb.NotificationRule, error) { c := &rule.HTTP{} c.SetID(id) c.SetTaskID(21) @@ -206,7 +207,7 @@ func TestNotificationRuleDelete(t *testing.T) { select { case id := <-ch: - if id != influxdb.ID(21) { + if id != platform.ID(21) { t.Fatalf("task sent to coordinator doesn't match expected") } default: diff --git a/task/backend/run_recorder.go b/task/backend/run_recorder.go index e203feb4f13..0de15cd17d3 100644 --- a/task/backend/run_recorder.go +++ b/task/backend/run_recorder.go @@ -6,6 +6,8 @@ import ( "fmt" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/models" "github.com/influxdata/influxdb/v2/storage" @@ -27,7 +29,7 @@ func NewStoragePointsWriterRecorder(log *zap.Logger, pw storage.PointsWriter) *S // Record formats the provided run as a models.Point and writes the resulting // point to an underlying storage.PointsWriter -func (s *StoragePointsWriterRecorder) Record(ctx context.Context, orgID influxdb.ID, org string, bucketID influxdb.ID, bucket string, run *influxdb.Run) error { +func (s *StoragePointsWriterRecorder) Record(ctx context.Context, orgID platform.ID, org string, bucketID platform.ID, bucket string, run *influxdb.Run) error { tags := models.NewTags(map[string]string{ statusTag: run.Status, taskIDTag: run.TaskID.String(), diff --git a/task/backend/schedulable_task_service.go b/task/backend/schedulable_task_service.go index f94c63622ca..cce2f77f271 100644 --- a/task/backend/schedulable_task_service.go +++ b/task/backend/schedulable_task_service.go @@ -5,6 +5,8 @@ import ( "fmt" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/task/backend/scheduler" ) @@ -13,7 +15,7 @@ var _ scheduler.SchedulableService = (*SchedulableTaskService)(nil) // UpdateTaskService provides an API to update the LatestScheduled time of a task type UpdateTaskService interface { - UpdateTask(ctx context.Context, id influxdb.ID, upd influxdb.TaskUpdate) (*influxdb.Task, error) + UpdateTask(ctx context.Context, id platform.ID, upd influxdb.TaskUpdate) (*influxdb.Task, error) } // SchedulableTaskService implements the SchedulableService interface @@ -28,7 +30,7 @@ func NewSchedulableTaskService(ts UpdateTaskService) SchedulableTaskService { // UpdateLastScheduled uses the task service to store the latest time a task was scheduled to run func (s SchedulableTaskService) UpdateLastScheduled(ctx context.Context, id scheduler.ID, t time.Time) error { - _, err := s.UpdateTask(ctx, influxdb.ID(id), influxdb.TaskUpdate{ + _, err := s.UpdateTask(ctx, platform.ID(id), influxdb.TaskUpdate{ LatestScheduled: &t, }) diff --git a/task/backend/schedulable_task_service_test.go b/task/backend/schedulable_task_service_test.go index 46c7281bacb..2a0277ed08c 100644 --- a/task/backend/schedulable_task_service_test.go +++ b/task/backend/schedulable_task_service_test.go @@ -5,16 +5,18 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/task/backend/scheduler" ) var ( - mockTaskID = influxdb.ID(1) + mockTaskID = platform.ID(1) mockTimeNow = time.Now() ) -func (m MockTaskService) UpdateTask(_ context.Context, id influxdb.ID, _ influxdb.TaskUpdate) (*influxdb.Task, error) { +func (m MockTaskService) UpdateTask(_ context.Context, id platform.ID, _ influxdb.TaskUpdate) (*influxdb.Task, error) { return &influxdb.Task{ID: id, UpdatedAt: mockTimeNow}, nil } diff --git a/task/backend/task.go b/task/backend/task.go index 0b7fc281078..05d4c257738 100644 --- a/task/backend/task.go +++ b/task/backend/task.go @@ -4,6 +4,8 @@ import ( "context" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -12,20 +14,20 @@ import ( type TaskControlService interface { // CreateRun creates a run with a scheduled for time. - CreateRun(ctx context.Context, taskID influxdb.ID, scheduledFor time.Time, runAt time.Time) (*influxdb.Run, error) + CreateRun(ctx context.Context, taskID platform.ID, scheduledFor time.Time, runAt time.Time) (*influxdb.Run, error) - CurrentlyRunning(ctx context.Context, taskID influxdb.ID) ([]*influxdb.Run, error) - ManualRuns(ctx context.Context, taskID influxdb.ID) ([]*influxdb.Run, error) + CurrentlyRunning(ctx context.Context, taskID platform.ID) ([]*influxdb.Run, error) + ManualRuns(ctx context.Context, taskID platform.ID) ([]*influxdb.Run, error) // StartManualRun pulls a manual run from the list and moves it to currently running. - StartManualRun(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) + StartManualRun(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) // FinishRun removes runID from the list of running tasks and if its `ScheduledFor` is later then last completed update it. - FinishRun(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) + FinishRun(ctx context.Context, taskID, runID platform.ID) (*influxdb.Run, error) // UpdateRunState sets the run state at the respective time. - UpdateRunState(ctx context.Context, taskID, runID influxdb.ID, when time.Time, state influxdb.RunStatus) error + UpdateRunState(ctx context.Context, taskID, runID platform.ID, when time.Time, state influxdb.RunStatus) error // AddRunLog adds a log line to the run. - AddRunLog(ctx context.Context, taskID, runID influxdb.ID, when time.Time, log string) error + AddRunLog(ctx context.Context, taskID, runID platform.ID, when time.Time, log string) error } diff --git a/task/mock/executor.go b/task/mock/executor.go index 05b51d8b2b5..d52e86c4943 100644 --- a/task/mock/executor.go +++ b/task/mock/executor.go @@ -7,6 +7,8 @@ import ( "sync" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/task/backend/executor" "github.com/influxdata/influxdb/v2/task/backend/scheduler" @@ -24,7 +26,7 @@ type promise struct { } // ID is the id of the run that was created -func (p *promise) ID() influxdb.ID { +func (p *promise) ID() platform.ID { return p.run.ID } @@ -101,7 +103,7 @@ func (e *Executor) Execute(ctx context.Context, id scheduler.ID, scheduledAt tim return nil } -func (e *Executor) ManualRun(ctx context.Context, id influxdb.ID, runID influxdb.ID) (executor.Promise, error) { +func (e *Executor) ManualRun(ctx context.Context, id platform.ID, runID platform.ID) (executor.Promise, error) { run := &influxdb.Run{ID: runID, TaskID: id, StartedAt: time.Now().UTC()} p, err := e.createPromise(ctx, run) return p, err @@ -111,7 +113,7 @@ func (e *Executor) Wait() { e.wg.Wait() } -func (e *Executor) Cancel(context.Context, influxdb.ID) error { +func (e *Executor) Cancel(context.Context, platform.ID) error { return nil } diff --git a/task/mock/task_control_service.go b/task/mock/task_control_service.go index eecac8d26d7..30e4f4c937a 100644 --- a/task/mock/task_control_service.go +++ b/task/mock/task_control_service.go @@ -7,6 +7,8 @@ import ( "sync" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/snowflake" "github.com/influxdata/influxdb/v2/task/backend" @@ -18,28 +20,28 @@ var idgen = snowflake.NewDefaultIDGenerator() type TaskControlService struct { mu sync.Mutex // Map of stringified task ID to last ID used for run. - runs map[influxdb.ID]map[influxdb.ID]*influxdb.Run + runs map[platform.ID]map[platform.ID]*influxdb.Run // Map of stringified, concatenated task and platform ID, to runs that have been created. created map[string]*influxdb.Run // Map of stringified task ID to task meta. - tasks map[influxdb.ID]*influxdb.Task + tasks map[platform.ID]*influxdb.Task manualRuns []*influxdb.Run // Map of task ID to total number of runs created for that task. - totalRunsCreated map[influxdb.ID]int - finishedRuns map[influxdb.ID]*influxdb.Run + totalRunsCreated map[platform.ID]int + finishedRuns map[platform.ID]*influxdb.Run } var _ backend.TaskControlService = (*TaskControlService)(nil) func NewTaskControlService() *TaskControlService { return &TaskControlService{ - runs: make(map[influxdb.ID]map[influxdb.ID]*influxdb.Run), - finishedRuns: make(map[influxdb.ID]*influxdb.Run), - tasks: make(map[influxdb.ID]*influxdb.Task), + runs: make(map[platform.ID]map[platform.ID]*influxdb.Run), + finishedRuns: make(map[platform.ID]*influxdb.Run), + tasks: make(map[platform.ID]*influxdb.Task), created: make(map[string]*influxdb.Run), - totalRunsCreated: make(map[influxdb.ID]int), + totalRunsCreated: make(map[platform.ID]int), } } @@ -56,14 +58,14 @@ func (d *TaskControlService) SetManualRuns(runs []*influxdb.Run) { d.manualRuns = runs } -func (t *TaskControlService) CreateRun(_ context.Context, taskID influxdb.ID, scheduledFor time.Time, runAt time.Time) (*influxdb.Run, error) { +func (t *TaskControlService) CreateRun(_ context.Context, taskID platform.ID, scheduledFor time.Time, runAt time.Time) (*influxdb.Run, error) { t.mu.Lock() defer t.mu.Unlock() runID := idgen.ID() runs, ok := t.runs[taskID] if !ok { - runs = make(map[influxdb.ID]*influxdb.Run) + runs = make(map[platform.ID]*influxdb.Run) } runs[runID] = &influxdb.Run{ ID: runID, @@ -73,7 +75,7 @@ func (t *TaskControlService) CreateRun(_ context.Context, taskID influxdb.ID, sc return runs[runID], nil } -func (t *TaskControlService) StartManualRun(_ context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (t *TaskControlService) StartManualRun(_ context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { t.mu.Lock() defer t.mu.Unlock() @@ -90,7 +92,7 @@ func (t *TaskControlService) StartManualRun(_ context.Context, taskID, runID inf return run, nil } -func (d *TaskControlService) FinishRun(_ context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) { +func (d *TaskControlService) FinishRun(_ context.Context, taskID, runID platform.ID) (*influxdb.Run, error) { d.mu.Lock() defer d.mu.Unlock() @@ -109,7 +111,7 @@ func (d *TaskControlService) FinishRun(_ context.Context, taskID, runID influxdb return r, nil } -func (t *TaskControlService) CurrentlyRunning(ctx context.Context, taskID influxdb.ID) ([]*influxdb.Run, error) { +func (t *TaskControlService) CurrentlyRunning(ctx context.Context, taskID platform.ID) ([]*influxdb.Run, error) { t.mu.Lock() defer t.mu.Unlock() rtn := []*influxdb.Run{} @@ -119,7 +121,7 @@ func (t *TaskControlService) CurrentlyRunning(ctx context.Context, taskID influx return rtn, nil } -func (t *TaskControlService) ManualRuns(ctx context.Context, taskID influxdb.ID) ([]*influxdb.Run, error) { +func (t *TaskControlService) ManualRuns(ctx context.Context, taskID platform.ID) ([]*influxdb.Run, error) { t.mu.Lock() defer t.mu.Unlock() @@ -130,7 +132,7 @@ func (t *TaskControlService) ManualRuns(ctx context.Context, taskID influxdb.ID) } // UpdateRunState sets the run state at the respective time. -func (d *TaskControlService) UpdateRunState(ctx context.Context, taskID, runID influxdb.ID, when time.Time, state influxdb.RunStatus) error { +func (d *TaskControlService) UpdateRunState(ctx context.Context, taskID, runID platform.ID, when time.Time, state influxdb.RunStatus) error { d.mu.Lock() defer d.mu.Unlock() @@ -153,7 +155,7 @@ func (d *TaskControlService) UpdateRunState(ctx context.Context, taskID, runID i } // AddRunLog adds a log line to the run. -func (d *TaskControlService) AddRunLog(ctx context.Context, taskID, runID influxdb.ID, when time.Time, log string) error { +func (d *TaskControlService) AddRunLog(ctx context.Context, taskID, runID platform.ID, when time.Time, log string) error { d.mu.Lock() defer d.mu.Unlock() @@ -165,7 +167,7 @@ func (d *TaskControlService) AddRunLog(ctx context.Context, taskID, runID influx return nil } -func (d *TaskControlService) CreatedFor(taskID influxdb.ID) []*influxdb.Run { +func (d *TaskControlService) CreatedFor(taskID platform.ID) []*influxdb.Run { d.mu.Lock() defer d.mu.Unlock() @@ -180,7 +182,7 @@ func (d *TaskControlService) CreatedFor(taskID influxdb.ID) []*influxdb.Run { } // TotalRunsCreatedForTask returns the number of runs created for taskID. -func (d *TaskControlService) TotalRunsCreatedForTask(taskID influxdb.ID) int { +func (d *TaskControlService) TotalRunsCreatedForTask(taskID platform.ID) int { d.mu.Lock() defer d.mu.Unlock() @@ -191,7 +193,7 @@ func (d *TaskControlService) TotalRunsCreatedForTask(taskID influxdb.ID) int { // If the expected number isn't found in time, it returns an error. // // Because the scheduler and executor do a lot of state changes asynchronously, this is useful in test. -func (d *TaskControlService) PollForNumberCreated(taskID influxdb.ID, count int) ([]*influxdb.Run, error) { +func (d *TaskControlService) PollForNumberCreated(taskID platform.ID, count int) ([]*influxdb.Run, error) { const numAttempts = 50 actualCount := 0 var created []*influxdb.Run @@ -206,7 +208,7 @@ func (d *TaskControlService) PollForNumberCreated(taskID influxdb.ID, count int) return created, fmt.Errorf("did not see count of %d created run(s) for task with ID %s in time, instead saw %d", count, taskID, actualCount) // we return created anyways, to make it easier to debug } -func (d *TaskControlService) FinishedRun(runID influxdb.ID) *influxdb.Run { +func (d *TaskControlService) FinishedRun(runID platform.ID) *influxdb.Run { d.mu.Lock() defer d.mu.Unlock() diff --git a/task/servicetest/servicetest.go b/task/servicetest/servicetest.go index 87ee0ee1a99..e7827d9bd29 100644 --- a/task/servicetest/servicetest.go +++ b/task/servicetest/servicetest.go @@ -16,6 +16,8 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" icontext "github.com/influxdata/influxdb/v2/context" @@ -125,7 +127,7 @@ func TestTaskService(t *testing.T, fn BackendComponentFactory, testCategory ...s // TestCreds encapsulates credentials needed for a system to properly work with tasks. type TestCreds struct { - OrgID, UserID, AuthorizationID influxdb.ID + OrgID, UserID, AuthorizationID platform.ID Org string Token string } @@ -205,7 +207,7 @@ func testTaskCRUD(t *testing.T, sys *System) { t.Fatal("no task ID set") } - findTask := func(tasks []*influxdb.Task, id influxdb.ID) (*influxdb.Task, error) { + findTask := func(tasks []*influxdb.Task, id platform.ID) (*influxdb.Task, error) { for _, t := range tasks { if t.ID == id { return t, nil @@ -586,7 +588,7 @@ from(bucket: "b") } var ( - expected = [][]influxdb.ID{ + expected = [][]platform.ID{ {created[0].ID, created[1].ID}, {created[2].ID, created[3].ID}, {created[4].ID, created[5].ID}, @@ -595,8 +597,8 @@ from(bucket: "b") // last page should be empty nil, } - found = make([][]influxdb.ID, 0, 6) - after *influxdb.ID + found = make([][]platform.ID, 0, 6) + after *platform.ID ) // one more than expected pages @@ -610,7 +612,7 @@ from(bucket: "b") t.Fatalf("FindTasks: %v", err) } - var page []influxdb.ID + var page []platform.ID for _, task := range tasks { page = append(page, task.ID) } @@ -980,13 +982,13 @@ func testTaskRuns(t *testing.T, sys *System) { } // Look for a run that doesn't exist. - _, err = sys.TaskService.FindRunByID(sys.Ctx, task.ID, influxdb.ID(math.MaxUint64)) + _, err = sys.TaskService.FindRunByID(sys.Ctx, task.ID, platform.ID(math.MaxUint64)) if err == nil { t.Fatalf("expected %s but got %s instead", influxdb.ErrRunNotFound, err) } // look for a taskID that doesn't exist. - _, err = sys.TaskService.FindRunByID(sys.Ctx, influxdb.ID(math.MaxUint64), runs[0].ID) + _, err = sys.TaskService.FindRunByID(sys.Ctx, platform.ID(math.MaxUint64), runs[0].ID) if err == nil { t.Fatalf("expected %s but got %s instead", influxdb.ErrRunNotFound, err) } @@ -1185,7 +1187,7 @@ func testTaskConcurrency(t *testing.T, sys *System) { // we need to keep a whitelist of IDs that are okay to delete. // This only matters when the creds function returns an identical user/org from another test. var idMu sync.Mutex - taskIDs := make(map[influxdb.ID]struct{}) + taskIDs := make(map[platform.ID]struct{}) var createWg sync.WaitGroup for i := 0; i < runtime.GOMAXPROCS(0); i++ { @@ -1308,7 +1310,7 @@ func testTaskConcurrency(t *testing.T, sys *System) { // Create a run for the last task we found. // The script should run every minute, so use max now. - var tid influxdb.ID + var tid platform.ID idMu.Lock() for i := len(tasks) - 1; i >= 0; i-- { _, ok := taskIDs[tasks[i].ID] @@ -1550,13 +1552,13 @@ func testRunStorage(t *testing.T, sys *System) { } // Look for a run that doesn't exist. - _, err = sys.TaskService.FindRunByID(sys.Ctx, task.ID, influxdb.ID(math.MaxUint64)) + _, err = sys.TaskService.FindRunByID(sys.Ctx, task.ID, platform.ID(math.MaxUint64)) if err == nil { t.Fatalf("expected %s but got %s instead", influxdb.ErrRunNotFound, err) } // look for a taskID that doesn't exist. - _, err = sys.TaskService.FindRunByID(sys.Ctx, influxdb.ID(math.MaxUint64), runs[0].ID) + _, err = sys.TaskService.FindRunByID(sys.Ctx, platform.ID(math.MaxUint64), runs[0].ID) if err == nil { t.Fatalf("expected %s but got %s instead", influxdb.ErrRunNotFound, err) } @@ -1593,7 +1595,7 @@ func testRetryAcrossStorage(t *testing.T, sys *System) { t.Fatal(err) } // Non-existent ID should return the right error. - _, err = sys.TaskService.RetryRun(sys.Ctx, task.ID, influxdb.ID(math.MaxUint64)) + _, err = sys.TaskService.RetryRun(sys.Ctx, task.ID, platform.ID(math.MaxUint64)) if !strings.Contains(err.Error(), "run not found") { t.Errorf("expected retrying run that doesn't exist to return %v, got %v", influxdb.ErrRunNotFound, err) } diff --git a/task_errors.go b/task_errors.go index 8c498d906c0..f90bb0fe20f 100644 --- a/task_errors.go +++ b/task_errors.go @@ -2,59 +2,61 @@ package influxdb import ( "fmt" + + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) var ( // ErrRunCanceled is returned from the RunResult when a Run is Canceled. It is used mostly internally. - ErrRunCanceled = &Error{ - Code: EInternal, + ErrRunCanceled = &errors.Error{ + Code: errors.EInternal, Msg: "run canceled", } // ErrTaskNotClaimed is returned when attempting to operate against a task that must be claimed but is not. - ErrTaskNotClaimed = &Error{ - Code: EConflict, + ErrTaskNotClaimed = &errors.Error{ + Code: errors.EConflict, Msg: "task not claimed", } // ErrTaskAlreadyClaimed is returned when attempting to operate against a task that must not be claimed but is. - ErrTaskAlreadyClaimed = &Error{ - Code: EConflict, + ErrTaskAlreadyClaimed = &errors.Error{ + Code: errors.EConflict, Msg: "task already claimed", } // ErrNoRunsFound is returned when searching for a range of runs, but none are found. - ErrNoRunsFound = &Error{ - Code: ENotFound, + ErrNoRunsFound = &errors.Error{ + Code: errors.ENotFound, Msg: "no matching runs found", } // ErrInvalidTaskID error object for bad id's - ErrInvalidTaskID = &Error{ - Code: EInvalid, + ErrInvalidTaskID = &errors.Error{ + Code: errors.EInvalid, Msg: "invalid id", } // ErrTaskNotFound indicates no task could be found for given parameters. - ErrTaskNotFound = &Error{ - Code: ENotFound, + ErrTaskNotFound = &errors.Error{ + Code: errors.ENotFound, Msg: "task not found", } // ErrRunNotFound is returned when searching for a single run that doesn't exist. - ErrRunNotFound = &Error{ - Code: ENotFound, + ErrRunNotFound = &errors.Error{ + Code: errors.ENotFound, Msg: "run not found", } - ErrRunKeyNotFound = &Error{ - Code: ENotFound, + ErrRunKeyNotFound = &errors.Error{ + Code: errors.ENotFound, Msg: "run key not found", } - ErrPageSizeTooSmall = &Error{ + ErrPageSizeTooSmall = &errors.Error{ Msg: "cannot have negative page limit", - Code: EInvalid, + Code: errors.EInvalid, } // ErrPageSizeTooLarge indicates the page size is too large. This error is only @@ -62,38 +64,38 @@ var ( // to be used in a place that is not useful. The TaskMaxPageSize is the only one // at 500, the rest at 100. This would likely benefit from a more specific name // since those limits aren't shared globally. - ErrPageSizeTooLarge = &Error{ + ErrPageSizeTooLarge = &errors.Error{ Msg: fmt.Sprintf("cannot use page size larger then %d", TaskMaxPageSize), - Code: EInvalid, + Code: errors.EInvalid, } - ErrOrgNotFound = &Error{ + ErrOrgNotFound = &errors.Error{ Msg: "organization not found", - Code: ENotFound, + Code: errors.ENotFound, } - ErrTaskRunAlreadyQueued = &Error{ + ErrTaskRunAlreadyQueued = &errors.Error{ Msg: "run already queued", - Code: EConflict, + Code: errors.EConflict, } // ErrOutOfBoundsLimit is returned with FindRuns is called with an invalid filter limit. - ErrOutOfBoundsLimit = &Error{ - Code: EUnprocessableEntity, + ErrOutOfBoundsLimit = &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: "run limit is out of bounds, must be between 1 and 500", } // ErrInvalidOwnerID is called when trying to create a task with out a valid ownerID - ErrInvalidOwnerID = &Error{ - Code: EInvalid, + ErrInvalidOwnerID = &errors.Error{ + Code: errors.EInvalid, Msg: "cannot create task with invalid ownerID", } ) // ErrFluxParseError is returned when an error is thrown by Flux.Parse in the task executor -func ErrFluxParseError(err error) *Error { - return &Error{ - Code: EInvalid, +func ErrFluxParseError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInvalid, Msg: "could not parse Flux script", Op: "taskExecutor", Err: err, @@ -101,9 +103,9 @@ func ErrFluxParseError(err error) *Error { } // ErrQueryError is returned when an error is thrown by Query service in the task executor -func ErrQueryError(err error) *Error { - return &Error{ - Code: EInternal, +func ErrQueryError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: "unexpected error from queryd", Op: "taskExecutor", Err: err, @@ -111,18 +113,18 @@ func ErrQueryError(err error) *Error { } // ErrResultIteratorError is returned when an error is thrown by exhaustResultIterators in the executor -func ErrResultIteratorError(err error) *Error { - return &Error{ - Code: EInvalid, +func ErrResultIteratorError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInvalid, Msg: "error exhausting result iterator", Op: "taskExecutor", Err: err, } } -func ErrInternalTaskServiceError(err error) *Error { - return &Error{ - Code: EInternal, +func ErrInternalTaskServiceError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: "unexpected error in tasks", Op: "task", Err: err, @@ -130,9 +132,9 @@ func ErrInternalTaskServiceError(err error) *Error { } // ErrUnexpectedTaskBucketErr a generic error we can use when we rail to retrieve a bucket -func ErrUnexpectedTaskBucketErr(err error) *Error { - return &Error{ - Code: EInternal, +func ErrUnexpectedTaskBucketErr(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: "unexpected error retrieving task bucket", Op: "taskBucket", Err: err, @@ -140,36 +142,36 @@ func ErrUnexpectedTaskBucketErr(err error) *Error { } // ErrTaskTimeParse an error for time parsing errors -func ErrTaskTimeParse(err error) *Error { - return &Error{ - Code: EInternal, +func ErrTaskTimeParse(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: "unexpected error parsing time", Op: "taskCron", Err: err, } } -func ErrTaskOptionParse(err error) *Error { - return &Error{ - Code: EInvalid, +func ErrTaskOptionParse(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInvalid, Msg: "invalid options", Op: "taskOptions", Err: err, } } -func ErrRunExecutionError(err error) *Error { - return &Error{ - Code: EInternal, +func ErrRunExecutionError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: "could not execute task run", Op: "taskExecutor", Err: err, } } -func ErrTaskConcurrencyLimitReached(runsInFront int) *Error { - return &Error{ - Code: ETooManyRequests, +func ErrTaskConcurrencyLimitReached(runsInFront int) *errors.Error { + return &errors.Error{ + Code: errors.ETooManyRequests, Msg: fmt.Sprintf("could not execute task, concurrency limit reached, runs in front: %d", runsInFront), Op: "taskExecutor", } diff --git a/telegraf.go b/telegraf.go index f93d9e722cf..d5f943e790b 100644 --- a/telegraf.go +++ b/telegraf.go @@ -6,6 +6,9 @@ import ( "fmt" "regexp" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/BurntSushi/toml" "github.com/influxdata/influxdb/v2/telegraf/plugins" "github.com/influxdata/influxdb/v2/telegraf/plugins/inputs" @@ -33,33 +36,33 @@ var ( // TelegrafConfigStore represents a service for managing telegraf config data. type TelegrafConfigStore interface { // FindTelegrafConfigByID returns a single telegraf config by ID. - FindTelegrafConfigByID(ctx context.Context, id ID) (*TelegrafConfig, error) + FindTelegrafConfigByID(ctx context.Context, id platform.ID) (*TelegrafConfig, error) // FindTelegrafConfigs returns a list of telegraf configs that match filter and the total count of matching telegraf configs. // Additional options provide pagination & sorting. FindTelegrafConfigs(ctx context.Context, filter TelegrafConfigFilter, opt ...FindOptions) ([]*TelegrafConfig, int, error) // CreateTelegrafConfig creates a new telegraf config and sets b.ID with the new identifier. - CreateTelegrafConfig(ctx context.Context, tc *TelegrafConfig, userID ID) error + CreateTelegrafConfig(ctx context.Context, tc *TelegrafConfig, userID platform.ID) error // UpdateTelegrafConfig updates a single telegraf config. // Returns the new telegraf config after update. - UpdateTelegrafConfig(ctx context.Context, id ID, tc *TelegrafConfig, userID ID) (*TelegrafConfig, error) + UpdateTelegrafConfig(ctx context.Context, id platform.ID, tc *TelegrafConfig, userID platform.ID) (*TelegrafConfig, error) // DeleteTelegrafConfig removes a telegraf config by ID. - DeleteTelegrafConfig(ctx context.Context, id ID) error + DeleteTelegrafConfig(ctx context.Context, id platform.ID) error } // TelegrafConfigFilter represents a set of filter that restrict the returned telegraf configs. type TelegrafConfigFilter struct { - OrgID *ID + OrgID *platform.ID Organization *string } // TelegrafConfig stores telegraf config for one telegraf instance. type TelegrafConfig struct { - ID ID `json:"id,omitempty"` // ID of this config object. - OrgID ID `json:"orgID,omitempty"` // OrgID is the id of the owning organization. + ID platform.ID `json:"id,omitempty"` // ID of this config object. + OrgID platform.ID `json:"orgID,omitempty"` // OrgID is the id of the owning organization. Name string `json:"name,omitempty"` // Name of this config object. Description string `json:"description,omitempty"` // Decription of this config object. Config string `json:"config,omitempty"` // ConfigTOML contains the raw toml config. @@ -147,8 +150,8 @@ type buckets []string func (t *buckets) UnmarshalTOML(data interface{}) error { dataOk, ok := data.(map[string]interface{}) if !ok { - return &Error{ - Code: EEmptyValue, + return &errors.Error{ + Code: errors.EEmptyValue, Msg: "no config to get buckets", } } @@ -159,8 +162,8 @@ func (t *buckets) UnmarshalTOML(data interface{}) error { } plugins, ok := ps.(map[string]interface{}) if !ok { - return &Error{ - Code: EEmptyValue, + return &errors.Error{ + Code: errors.EEmptyValue, Msg: "no plugins in config to get buckets", } } @@ -170,8 +173,8 @@ func (t *buckets) UnmarshalTOML(data interface{}) error { } config, ok := configDataArray.([]map[string]interface{}) if !ok { - return &Error{ - Code: EEmptyValue, + return &errors.Error{ + Code: errors.EEmptyValue, Msg: "influxdb_v2 output has no config", } } @@ -222,16 +225,16 @@ func decodePluginRaw(tcd *telegrafConfigDecode) ([]string, string, error) { case "output": tpFn, ok = availableOutputPlugins[pr.Name] default: - return nil, "", &Error{ - Code: EInvalid, + return nil, "", &errors.Error{ + Code: errors.EInvalid, Op: op, Msg: fmt.Sprintf(ErrUnsupportTelegrafPluginType, pr.Type), } } if !ok { - return nil, "", &Error{ - Code: EInvalid, + return nil, "", &errors.Error{ + Code: errors.EInvalid, Op: op, Msg: fmt.Sprintf(ErrUnsupportTelegrafPluginName, pr.Name, pr.Type), } @@ -245,8 +248,8 @@ func decodePluginRaw(tcd *telegrafConfigDecode) ([]string, string, error) { } if err := json.Unmarshal(pr.Config, config); err != nil { - return nil, "", &Error{ - Code: EInvalid, + return nil, "", &errors.Error{ + Code: errors.EInvalid, Err: err, Op: op, } @@ -266,9 +269,9 @@ func decodePluginRaw(tcd *telegrafConfigDecode) ([]string, string, error) { // telegrafConfigDecode is the helper struct for json decoding. legacy. type telegrafConfigDecode struct { - ID *ID `json:"id,omitempty"` - OrganizationID *ID `json:"organizationID,omitempty"` - OrgID *ID `json:"orgID,omitempty"` + ID *platform.ID `json:"id,omitempty"` + OrganizationID *platform.ID `json:"organizationID,omitempty"` + OrgID *platform.ID `json:"orgID,omitempty"` Name string `json:"name,omitempty"` Description string `json:"description,omitempty"` Config string `json:"config,omitempty"` diff --git a/telegraf/service/telegraf.go b/telegraf/service/telegraf.go index 6598908e96c..31a043fe3d9 100644 --- a/telegraf/service/telegraf.go +++ b/telegraf/service/telegraf.go @@ -5,6 +5,9 @@ import ( "encoding/json" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + influxdb "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" "github.com/influxdata/influxdb/v2/snowflake" @@ -13,30 +16,30 @@ import ( var ( // ErrTelegrafNotFound is used when the telegraf configuration is not found. - ErrTelegrafNotFound = &influxdb.Error{ + ErrTelegrafNotFound = &errors.Error{ Msg: "telegraf configuration not found", - Code: influxdb.ENotFound, + Code: errors.ENotFound, } // ErrInvalidTelegrafID is used when the service was provided // an invalid ID format. - ErrInvalidTelegrafID = &influxdb.Error{ - Code: influxdb.EInvalid, + ErrInvalidTelegrafID = &errors.Error{ + Code: errors.EInvalid, Msg: "provided telegraf configuration ID has invalid format", } // ErrInvalidTelegrafOrgID is the error message for a missing or invalid organization ID. - ErrInvalidTelegrafOrgID = &influxdb.Error{ - Code: influxdb.EEmptyValue, + ErrInvalidTelegrafOrgID = &errors.Error{ + Code: errors.EEmptyValue, Msg: "provided telegraf configuration organization ID is missing or invalid", } ) // UnavailableTelegrafServiceError is used if we aren't able to interact with the // store, it means the store is not available at the moment (e.g. network). -func UnavailableTelegrafServiceError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func UnavailableTelegrafServiceError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("Unable to connect to telegraf service. Please try again; Err: %v", err), Op: "kv/telegraf", } @@ -44,9 +47,9 @@ func UnavailableTelegrafServiceError(err error) *influxdb.Error { // InternalTelegrafServiceError is used when the error comes from an // internal system. -func InternalTelegrafServiceError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func InternalTelegrafServiceError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("Unknown internal telegraf data error; Err: %v", err), Op: "kv/telegraf", } @@ -54,18 +57,18 @@ func InternalTelegrafServiceError(err error) *influxdb.Error { // CorruptTelegrafError is used when the config cannot be unmarshalled from the // bytes stored in the kv. -func CorruptTelegrafError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func CorruptTelegrafError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("Unknown internal telegraf data error; Err: %v", err), Op: "kv/telegraf", } } // ErrUnprocessableTelegraf is used when a telegraf is not able to be converted to JSON. -func ErrUnprocessableTelegraf(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, +func ErrUnprocessableTelegraf(err error) *errors.Error { + return &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: fmt.Sprintf("unable to convert telegraf configuration into JSON; Err %v", err), } } @@ -83,7 +86,7 @@ type Service struct { byOrganisationIndex *kv.Index - IDGenerator influxdb.IDGenerator + IDGenerator platform.IDGenerator } // New constructs and configures a new telegraf config service. @@ -115,7 +118,7 @@ func (s *Service) telegrafPluginsBucket(tx kv.Tx) (kv.Bucket, error) { } // FindTelegrafConfigByID returns a single telegraf config by ID. -func (s *Service) FindTelegrafConfigByID(ctx context.Context, id influxdb.ID) (*influxdb.TelegrafConfig, error) { +func (s *Service) FindTelegrafConfigByID(ctx context.Context, id platform.ID) (*influxdb.TelegrafConfig, error) { var ( tc *influxdb.TelegrafConfig err error @@ -129,7 +132,7 @@ func (s *Service) FindTelegrafConfigByID(ctx context.Context, id influxdb.ID) (* return tc, err } -func (s *Service) findTelegrafConfigByID(ctx context.Context, tx kv.Tx, id influxdb.ID) (*influxdb.TelegrafConfig, error) { +func (s *Service) findTelegrafConfigByID(ctx context.Context, tx kv.Tx, id platform.ID) (*influxdb.TelegrafConfig, error) { encID, err := id.Encode() if err != nil { return nil, ErrInvalidTelegrafID @@ -284,13 +287,13 @@ func (s *Service) putTelegrafConfigStats(encodedID []byte, tx kv.Tx, tc *influxd } // CreateTelegrafConfig creates a new telegraf config and sets b.ID with the new identifier. -func (s *Service) CreateTelegrafConfig(ctx context.Context, tc *influxdb.TelegrafConfig, userID influxdb.ID) error { +func (s *Service) CreateTelegrafConfig(ctx context.Context, tc *influxdb.TelegrafConfig, userID platform.ID) error { return s.kv.Update(ctx, func(tx kv.Tx) error { return s.createTelegrafConfig(ctx, tx, tc, userID) }) } -func (s *Service) createTelegrafConfig(ctx context.Context, tx kv.Tx, tc *influxdb.TelegrafConfig, userID influxdb.ID) error { +func (s *Service) createTelegrafConfig(ctx context.Context, tx kv.Tx, tc *influxdb.TelegrafConfig, userID platform.ID) error { tc.ID = s.IDGenerator.ID() return s.putTelegrafConfig(ctx, tx, tc) @@ -298,7 +301,7 @@ func (s *Service) createTelegrafConfig(ctx context.Context, tx kv.Tx, tc *influx // UpdateTelegrafConfig updates a single telegraf config. // Returns the new telegraf config after update. -func (s *Service) UpdateTelegrafConfig(ctx context.Context, id influxdb.ID, tc *influxdb.TelegrafConfig, userID influxdb.ID) (*influxdb.TelegrafConfig, error) { +func (s *Service) UpdateTelegrafConfig(ctx context.Context, id platform.ID, tc *influxdb.TelegrafConfig, userID platform.ID) (*influxdb.TelegrafConfig, error) { var err error err = s.kv.Update(ctx, func(tx kv.Tx) error { tc, err = s.updateTelegrafConfig(ctx, tx, id, tc, userID) @@ -307,7 +310,7 @@ func (s *Service) UpdateTelegrafConfig(ctx context.Context, id influxdb.ID, tc * return tc, err } -func (s *Service) updateTelegrafConfig(ctx context.Context, tx kv.Tx, id influxdb.ID, tc *influxdb.TelegrafConfig, userID influxdb.ID) (*influxdb.TelegrafConfig, error) { +func (s *Service) updateTelegrafConfig(ctx context.Context, tx kv.Tx, id platform.ID, tc *influxdb.TelegrafConfig, userID platform.ID) (*influxdb.TelegrafConfig, error) { current, err := s.findTelegrafConfigByID(ctx, tx, id) if err != nil { return nil, err @@ -321,13 +324,13 @@ func (s *Service) updateTelegrafConfig(ctx context.Context, tx kv.Tx, id influxd } // DeleteTelegrafConfig removes a telegraf config by ID. -func (s *Service) DeleteTelegrafConfig(ctx context.Context, id influxdb.ID) error { +func (s *Service) DeleteTelegrafConfig(ctx context.Context, id platform.ID) error { return s.kv.Update(ctx, func(tx kv.Tx) error { return s.deleteTelegrafConfig(ctx, tx, id) }) } -func (s *Service) deleteTelegrafConfig(ctx context.Context, tx kv.Tx, id influxdb.ID) error { +func (s *Service) deleteTelegrafConfig(ctx context.Context, tx kv.Tx, id platform.ID) error { tc, err := s.findTelegrafConfigByID(ctx, tx, id) if err != nil { return err @@ -375,8 +378,8 @@ func (s *Service) deleteTelegrafConfigStats(encodedID []byte, tx kv.Tx) error { } if err := bucket.Delete(encodedID); err != nil { - return &influxdb.Error{ - Code: influxdb.EInternal, + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("Unable to connect to telegraf config stats service. Please try again; Err: %v", err), Op: "kv/telegraf", } diff --git a/telegraf/service/testing/testing.go b/telegraf/service/testing/testing.go index 82db4c8ebe9..2414bfec323 100644 --- a/telegraf/service/testing/testing.go +++ b/telegraf/service/testing/testing.go @@ -6,6 +6,9 @@ import ( "sort" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" influxdb "github.com/influxdata/influxdb/v2" @@ -17,15 +20,15 @@ import ( ) var ( - oneID = influxdb.ID(1) - twoID = influxdb.ID(2) - threeID = influxdb.ID(3) - fourID = influxdb.ID(4) + oneID = platform.ID(1) + twoID = platform.ID(2) + threeID = platform.ID(3) + fourID = platform.ID(4) ) // TelegrafConfigFields includes prepopulated data for mapping tests. type TelegrafConfigFields struct { - IDGenerator influxdb.IDGenerator + IDGenerator platform.IDGenerator TelegrafConfigs []*influxdb.TelegrafConfig } @@ -95,7 +98,7 @@ func CreateTelegrafConfig( ) { type args struct { telegrafConfig *influxdb.TelegrafConfig - userID influxdb.ID + userID platform.ID } type wants struct { err error @@ -118,8 +121,8 @@ func CreateTelegrafConfig( telegrafConfig: &influxdb.TelegrafConfig{}, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EEmptyValue, + err: &errors.Error{ + Code: errors.EEmptyValue, Msg: influxdb.ErrTelegrafConfigInvalidOrgID, }, }, @@ -209,8 +212,8 @@ func CreateTelegrafConfig( } if err != nil && tt.wants.err != nil { - if influxdb.ErrorCode(err) != influxdb.ErrorCode(tt.wants.err) { - t.Fatalf("expected error messages to match '%v' got '%v'", influxdb.ErrorCode(tt.wants.err), influxdb.ErrorCode(err)) + if errors.ErrorCode(err) != errors.ErrorCode(tt.wants.err) { + t.Fatalf("expected error messages to match '%v' got '%v'", errors.ErrorCode(tt.wants.err), errors.ErrorCode(err)) } } @@ -232,7 +235,7 @@ func FindTelegrafConfigByID( t *testing.T, ) { type args struct { - id influxdb.ID + id platform.ID } type wants struct { err error @@ -266,7 +269,7 @@ func FindTelegrafConfigByID( }, }, args: args{ - id: influxdb.ID(0), + id: platform.ID(0), }, wants: wants{ err: fmt.Errorf("provided telegraf configuration ID has invalid format"), @@ -294,8 +297,8 @@ func FindTelegrafConfigByID( id: threeID, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "telegraf configuration not found", }, }, @@ -603,8 +606,8 @@ func UpdateTelegrafConfig( t *testing.T, ) { type args struct { - userID influxdb.ID - id influxdb.ID + userID platform.ID + id platform.ID telegrafConfig *influxdb.TelegrafConfig } @@ -645,8 +648,8 @@ func UpdateTelegrafConfig( }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: fmt.Sprintf("telegraf config with ID %v not found", fourID), }, }, @@ -736,7 +739,7 @@ func UpdateTelegrafConfig( t.Fatalf("expected errors to be nil got '%v'", err) } if err != nil && tt.wants.err != nil { - if influxdb.ErrorCode(err) != influxdb.ErrorCode(tt.wants.err) { + if errors.ErrorCode(err) != errors.ErrorCode(tt.wants.err) { t.Fatalf("expected error '%v' got '%v'", tt.wants.err, err) } } @@ -754,7 +757,7 @@ func DeleteTelegrafConfig( t *testing.T, ) { type args struct { - id influxdb.ID + id platform.ID } type wants struct { @@ -789,7 +792,7 @@ func DeleteTelegrafConfig( }, }, args: args{ - id: influxdb.ID(0), + id: platform.ID(0), }, wants: wants{ err: fmt.Errorf("provided telegraf configuration ID has invalid format"), diff --git a/telegraf_test.go b/telegraf_test.go index 1539d373bfa..76f2158442f 100644 --- a/telegraf_test.go +++ b/telegraf_test.go @@ -6,6 +6,9 @@ import ( "sort" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/influxdata/influxdb/v2/telegraf/plugins" @@ -278,9 +281,9 @@ func TestTelegrafConfigJSONDecodeTOML(t *testing.T) { } func TestTelegrafConfigJSONCompatibleMode(t *testing.T) { - id1, _ := IDFromString("020f755c3c082000") - id2, _ := IDFromString("020f755c3c082222") - id3, _ := IDFromString("020f755c3c082223") + id1, _ := platform.IDFromString("020f755c3c082000") + id2, _ := platform.IDFromString("020f755c3c082222") + id3, _ := platform.IDFromString("020f755c3c082223") cases := []struct { name string src []byte @@ -337,8 +340,8 @@ func TestTelegrafConfigJSONCompatibleMode(t *testing.T) { } func TestTelegrafConfigJSON(t *testing.T) { - id1, _ := IDFromString("020f755c3c082000") - id2, _ := IDFromString("020f755c3c082222") + id1, _ := platform.IDFromString("020f755c3c082000") + id2, _ := platform.IDFromString("020f755c3c082222") cases := []struct { name string expect *TelegrafConfig @@ -417,8 +420,8 @@ func TestTelegrafConfigJSON(t *testing.T) { } ] }`, *id1, *id2), - err: &Error{ - Code: EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf(ErrUnsupportTelegrafPluginType, "aggregator"), Op: "unmarshal telegraf config raw plugin", }, @@ -439,8 +442,8 @@ func TestTelegrafConfigJSON(t *testing.T) { } ] }`, *id1, *id2), - err: &Error{ - Code: EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf(ErrUnsupportTelegrafPluginName, "kafka", plugins.Output), Op: "unmarshal telegraf config raw plugin", }, @@ -460,7 +463,7 @@ func TestTelegrafConfigJSON(t *testing.T) { } func TestLegacyStruct(t *testing.T) { - id1, _ := IDFromString("020f755c3c082000") + id1, _ := platform.IDFromString("020f755c3c082000") telConfOld := fmt.Sprintf(`{ "id": "%v", diff --git a/tenant/error.go b/tenant/error.go index 6f1885165f9..ee9beb04f07 100644 --- a/tenant/error.go +++ b/tenant/error.go @@ -4,51 +4,51 @@ import ( "fmt" "strings" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) var ( // ErrNameisEmpty is when a name is empty - ErrNameisEmpty = &influxdb.Error{ - Code: influxdb.EInvalid, + ErrNameisEmpty = &errors.Error{ + Code: errors.EInvalid, Msg: "name is empty", } // ErrIDNotUnique is used when attempting to create an org or bucket that already // exists. - ErrIDNotUnique = &influxdb.Error{ - Code: influxdb.EConflict, + ErrIDNotUnique = &errors.Error{ + Code: errors.EConflict, Msg: "ID already exists", } // ErrFailureGeneratingID occurs ony when the random number generator // cannot generate an ID in MaxIDGenerationN times. - ErrFailureGeneratingID = &influxdb.Error{ - Code: influxdb.EInternal, + ErrFailureGeneratingID = &errors.Error{ + Code: errors.EInternal, Msg: "unable to generate valid id", } // ErrOnboardingNotAllowed occurs when request to onboard comes in and we are not allowing this request - ErrOnboardingNotAllowed = &influxdb.Error{ - Code: influxdb.EConflict, + ErrOnboardingNotAllowed = &errors.Error{ + Code: errors.EConflict, Msg: "onboarding has already been completed", } - ErrOnboardInvalid = &influxdb.Error{ - Code: influxdb.EEmptyValue, + ErrOnboardInvalid = &errors.Error{ + Code: errors.EEmptyValue, Msg: "onboard failed, missing value", } - ErrNotFound = &influxdb.Error{ - Code: influxdb.ENotFound, + ErrNotFound = &errors.Error{ + Code: errors.ENotFound, Msg: "not found", } ) // ErrInternalServiceError is used when the error comes from an internal system. -func ErrInternalServiceError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func ErrInternalServiceError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Err: err, } } diff --git a/tenant/error_bucket.go b/tenant/error_bucket.go index 7412683b2c7..4c7c61beb5b 100644 --- a/tenant/error_bucket.go +++ b/tenant/error_bucket.go @@ -3,50 +3,50 @@ package tenant import ( "fmt" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) var ( - invalidBucketListRequest = &influxdb.Error{ - Code: influxdb.EInternal, + invalidBucketListRequest = &errors.Error{ + Code: errors.EInternal, Msg: "invalid bucket list action, call should be GetBucketByName", Op: "kv/listBucket", } - errRenameSystemBucket = &influxdb.Error{ - Code: influxdb.EInvalid, + errRenameSystemBucket = &errors.Error{ + Code: errors.EInvalid, Msg: "system buckets cannot be renamed", } - errDeleteSystemBucket = &influxdb.Error{ - Code: influxdb.EInvalid, + errDeleteSystemBucket = &errors.Error{ + Code: errors.EInvalid, Msg: "system buckets cannot be deleted", } - ErrBucketNotFound = &influxdb.Error{ - Code: influxdb.ENotFound, + ErrBucketNotFound = &errors.Error{ + Code: errors.ENotFound, Msg: "bucket not found", } - ErrBucketNameNotUnique = &influxdb.Error{ - Code: influxdb.EConflict, + ErrBucketNameNotUnique = &errors.Error{ + Code: errors.EConflict, Msg: "bucket name is not unique", } ) // ErrBucketNotFoundByName is used when the user is not found. -func ErrBucketNotFoundByName(n string) *influxdb.Error { - return &influxdb.Error{ +func ErrBucketNotFoundByName(n string) *errors.Error { + return &errors.Error{ Msg: fmt.Sprintf("bucket %q not found", n), - Code: influxdb.ENotFound, + Code: errors.ENotFound, } } // ErrCorruptBucket is used when the user cannot be unmarshalled from the bytes // stored in the kv. -func ErrCorruptBucket(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func ErrCorruptBucket(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: "user could not be unmarshalled", Err: err, Op: "kv/UnmarshalBucket", @@ -55,17 +55,17 @@ func ErrCorruptBucket(err error) *influxdb.Error { // BucketAlreadyExistsError is used when attempting to create a user with a name // that already exists. -func BucketAlreadyExistsError(n string) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EConflict, +func BucketAlreadyExistsError(n string) *errors.Error { + return &errors.Error{ + Code: errors.EConflict, Msg: fmt.Sprintf("bucket with name %s already exists", n), } } // ErrUnprocessableBucket is used when a org is not able to be processed. -func ErrUnprocessableBucket(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, +func ErrUnprocessableBucket(err error) *errors.Error { + return &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: "user could not be marshalled", Err: err, Op: "kv/MarshalBucket", diff --git a/tenant/error_org.go b/tenant/error_org.go index 2db58741910..b80240a08b1 100644 --- a/tenant/error_org.go +++ b/tenant/error_org.go @@ -3,29 +3,31 @@ package tenant import ( "fmt" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) var ( // ErrOrgNotFound is used when the user is not found. - ErrOrgNotFound = &influxdb.Error{ + ErrOrgNotFound = &errors.Error{ Msg: "organization not found", - Code: influxdb.ENotFound, + Code: errors.ENotFound, } ) // OrgAlreadyExistsError is used when creating a new organization with // a name that has already been used. Organization names must be unique. func OrgAlreadyExistsError(name string) error { - return &influxdb.Error{ - Code: influxdb.EConflict, + return &errors.Error{ + Code: errors.EConflict, Msg: fmt.Sprintf("organization with name %s already exists", name), } } func OrgNotFoundByName(name string) error { - return &influxdb.Error{ - Code: influxdb.ENotFound, + return &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindOrganizations, Msg: fmt.Sprintf("organization name \"%s\" not found", name), } @@ -33,9 +35,9 @@ func OrgNotFoundByName(name string) error { // ErrCorruptOrg is used when the user cannot be unmarshalled from the bytes // stored in the kv. -func ErrCorruptOrg(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func ErrCorruptOrg(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: "user could not be unmarshalled", Err: err, Op: "kv/UnmarshalOrg", @@ -43,9 +45,9 @@ func ErrCorruptOrg(err error) *influxdb.Error { } // ErrUnprocessableOrg is used when a org is not able to be processed. -func ErrUnprocessableOrg(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, +func ErrUnprocessableOrg(err error) *errors.Error { + return &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: "user could not be marshalled", Err: err, Op: "kv/MarshalOrg", @@ -54,9 +56,9 @@ func ErrUnprocessableOrg(err error) *influxdb.Error { // InvalidOrgIDError is used when a service was provided an invalid ID. // This is some sort of internal server error. -func InvalidOrgIDError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInvalid, +func InvalidOrgIDError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInvalid, Msg: "org id provided is invalid", Err: err, } diff --git a/tenant/error_urm.go b/tenant/error_urm.go index ced00eefaa8..6da953fa081 100644 --- a/tenant/error_urm.go +++ b/tenant/error_urm.go @@ -3,29 +3,30 @@ package tenant import ( "fmt" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) var ( // ErrInvalidURMID is used when the service was provided // an invalid ID format. - ErrInvalidURMID = &influxdb.Error{ - Code: influxdb.EInvalid, + ErrInvalidURMID = &errors.Error{ + Code: errors.EInvalid, Msg: "provided user resource mapping ID has invalid format", } // ErrURMNotFound is used when the user resource mapping is not found. - ErrURMNotFound = &influxdb.Error{ + ErrURMNotFound = &errors.Error{ Msg: "user to resource mapping not found", - Code: influxdb.ENotFound, + Code: errors.ENotFound, } ) // UnavailableURMServiceError is used if we aren't able to interact with the // store, it means the store is not available at the moment (e.g. network). -func UnavailableURMServiceError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func UnavailableURMServiceError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("Unable to connect to resource mapping service. Please try again; Err: %v", err), Op: "kv/userResourceMapping", } @@ -33,27 +34,27 @@ func UnavailableURMServiceError(err error) *influxdb.Error { // CorruptURMError is used when the config cannot be unmarshalled from the // bytes stored in the kv. -func CorruptURMError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func CorruptURMError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("Unknown internal user resource mapping data error; Err: %v", err), Op: "kv/userResourceMapping", } } // ErrUnprocessableMapping is used when a user resource mapping is not able to be converted to JSON. -func ErrUnprocessableMapping(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, +func ErrUnprocessableMapping(err error) *errors.Error { + return &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: fmt.Sprintf("unable to convert mapping of user to resource into JSON; Err %v", err), } } // NonUniqueMappingError is an internal error when a user already has // been mapped to a resource -func NonUniqueMappingError(userID influxdb.ID) error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func NonUniqueMappingError(userID platform.ID) error { + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("Unexpected error when assigning user to a resource: mapping for user %s already exists", userID.String()), } } diff --git a/tenant/error_user.go b/tenant/error_user.go index 05aa1892dd7..3861aca0889 100644 --- a/tenant/error_user.go +++ b/tenant/error_user.go @@ -3,62 +3,62 @@ package tenant import ( "fmt" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) const MinPasswordLen int = 8 var ( // ErrUserNotFound is used when the user is not found. - ErrUserNotFound = &influxdb.Error{ + ErrUserNotFound = &errors.Error{ Msg: "user not found", - Code: influxdb.ENotFound, + Code: errors.ENotFound, } // EIncorrectPassword is returned when any password operation fails in which // we do not want to leak information. - EIncorrectPassword = &influxdb.Error{ - Code: influxdb.EForbidden, + EIncorrectPassword = &errors.Error{ + Code: errors.EForbidden, Msg: "your username or password is incorrect", } // EIncorrectUser is returned when any user is failed to be found which indicates // the userID provided is for a user that does not exist. - EIncorrectUser = &influxdb.Error{ - Code: influxdb.EForbidden, + EIncorrectUser = &errors.Error{ + Code: errors.EForbidden, Msg: "your userID is incorrect", } // EShortPassword is used when a password is less than the minimum // acceptable password length. - EShortPassword = &influxdb.Error{ - Code: influxdb.EInvalid, + EShortPassword = &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("passwords must be at least %d characters long", MinPasswordLen), } ) // UserAlreadyExistsError is used when attempting to create a user with a name // that already exists. -func UserAlreadyExistsError(n string) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EConflict, +func UserAlreadyExistsError(n string) *errors.Error { + return &errors.Error{ + Code: errors.EConflict, Msg: fmt.Sprintf("user with name %s already exists", n), } } // UnexpectedUserBucketError is used when the error comes from an internal system. -func UnexpectedUserBucketError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func UnexpectedUserBucketError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("unexpected error retrieving user bucket; Err: %v", err), Op: "kv/userBucket", } } // UnexpectedUserIndexError is used when the error comes from an internal system. -func UnexpectedUserIndexError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func UnexpectedUserIndexError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("unexpected error retrieving user index; Err: %v", err), Op: "kv/userIndex", } @@ -66,9 +66,9 @@ func UnexpectedUserIndexError(err error) *influxdb.Error { // InvalidUserIDError is used when a service was provided an invalid ID. // This is some sort of internal server error. -func InvalidUserIDError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInvalid, +func InvalidUserIDError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInvalid, Msg: "user id provided is invalid", Err: err, } @@ -76,9 +76,9 @@ func InvalidUserIDError(err error) *influxdb.Error { // ErrCorruptUser is used when the user cannot be unmarshalled from the bytes // stored in the kv. -func ErrCorruptUser(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func ErrCorruptUser(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: "user could not be unmarshalled", Err: err, Op: "kv/UnmarshalUser", @@ -86,9 +86,9 @@ func ErrCorruptUser(err error) *influxdb.Error { } // ErrUnprocessableUser is used when a user is not able to be processed. -func ErrUnprocessableUser(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, +func ErrUnprocessableUser(err error) *errors.Error { + return &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: "user could not be marshalled", Err: err, Op: "kv/MarshalUser", @@ -98,9 +98,9 @@ func ErrUnprocessableUser(err error) *influxdb.Error { // UnavailablePasswordServiceError is used if we aren't able to add the // password to the store, it means the store is not available at the moment // (e.g. network). -func UnavailablePasswordServiceError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EUnavailable, +func UnavailablePasswordServiceError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EUnavailable, Msg: fmt.Sprintf("Unable to connect to password service. Please try again; Err: %v", err), Op: "kv/setPassword", } diff --git a/tenant/http_client_bucket.go b/tenant/http_client_bucket.go index 0e9cc8af968..39d22c0362e 100644 --- a/tenant/http_client_bucket.go +++ b/tenant/http_client_bucket.go @@ -5,6 +5,9 @@ import ( "fmt" "path" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/tracing" "github.com/influxdata/influxdb/v2/pkg/httpc" @@ -19,13 +22,13 @@ type BucketClientService struct { } // FindBucketByName returns a single bucket by name -func (s *BucketClientService) FindBucketByName(ctx context.Context, orgID influxdb.ID, name string) (*influxdb.Bucket, error) { +func (s *BucketClientService) FindBucketByName(ctx context.Context, orgID platform.ID, name string) (*influxdb.Bucket, error) { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() if name == "" { - return nil, &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + return nil, &errors.Error{ + Code: errors.EUnprocessableEntity, Op: s.OpPrefix + influxdb.OpFindBuckets, Msg: "bucket name is required", } @@ -39,8 +42,8 @@ func (s *BucketClientService) FindBucketByName(ctx context.Context, orgID influx return nil, err } if n == 0 || len(bkts) == 0 { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Op: s.OpPrefix + influxdb.OpFindBucket, Msg: fmt.Sprintf("bucket %q not found", name), } @@ -50,7 +53,7 @@ func (s *BucketClientService) FindBucketByName(ctx context.Context, orgID influx } // FindBucketByID returns a single bucket by ID. -func (s *BucketClientService) FindBucketByID(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { +func (s *BucketClientService) FindBucketByID(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { // TODO(@jsteenb2): are tracing span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -77,14 +80,14 @@ func (s *BucketClientService) FindBucket(ctx context.Context, filter influxdb.Bu } if n == 0 && filter.Name != nil { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Op: s.OpPrefix + influxdb.OpFindBucket, Msg: fmt.Sprintf("bucket %q not found", *filter.Name), } } else if n == 0 { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Op: s.OpPrefix + influxdb.OpFindBucket, Msg: "bucket not found", } @@ -152,7 +155,7 @@ func (s *BucketClientService) CreateBucket(ctx context.Context, b *influxdb.Buck // UpdateBucket updates a single bucket with changeset. // Returns the new bucket state after update. -func (s *BucketClientService) UpdateBucket(ctx context.Context, id influxdb.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { +func (s *BucketClientService) UpdateBucket(ctx context.Context, id platform.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { var br bucketResponse err := s.Client. PatchJSON(newBucketUpdate(&upd), path.Join(prefixBuckets, id.String())). @@ -165,7 +168,7 @@ func (s *BucketClientService) UpdateBucket(ctx context.Context, id influxdb.ID, } // DeleteBucket removes a bucket by ID. -func (s *BucketClientService) DeleteBucket(ctx context.Context, id influxdb.ID) error { +func (s *BucketClientService) DeleteBucket(ctx context.Context, id platform.ID) error { return s.Client. Delete(path.Join(prefixBuckets, id.String())). Do(ctx) diff --git a/tenant/http_client_org.go b/tenant/http_client_org.go index bfa7990e1f7..722c7e82478 100644 --- a/tenant/http_client_org.go +++ b/tenant/http_client_org.go @@ -3,6 +3,9 @@ package tenant import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/tracing" "github.com/influxdata/influxdb/v2/pkg/httpc" @@ -24,11 +27,11 @@ func (o orgsResponse) toInfluxdb() []*influxdb.Organization { } // FindOrganizationByID gets a single organization with a given id using HTTP. -func (s *OrgClientService) FindOrganizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { +func (s *OrgClientService) FindOrganizationByID(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { filter := influxdb.OrganizationFilter{ID: &id} o, err := s.FindOrganization(ctx, filter) if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, Op: s.OpPrefix + influxdb.OpFindOrganizationByID, } @@ -43,15 +46,15 @@ func (s *OrgClientService) FindOrganization(ctx context.Context, filter influxdb } os, n, err := s.FindOrganizations(ctx, filter) if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, Op: s.OpPrefix + influxdb.OpFindOrganization, } } if n == 0 { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Op: s.OpPrefix + influxdb.OpFindOrganization, Msg: "organization not found", } @@ -120,7 +123,7 @@ func (s *OrgClientService) CreateOrganization(ctx context.Context, o *influxdb.O } // UpdateOrganization updates the organization over HTTP. -func (s *OrgClientService) UpdateOrganization(ctx context.Context, id influxdb.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { +func (s *OrgClientService) UpdateOrganization(ctx context.Context, id platform.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -140,7 +143,7 @@ func (s *OrgClientService) UpdateOrganization(ctx context.Context, id influxdb.I } // DeleteOrganization removes organization id over HTTP. -func (s *OrgClientService) DeleteOrganization(ctx context.Context, id influxdb.ID) error { +func (s *OrgClientService) DeleteOrganization(ctx context.Context, id platform.ID) error { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() diff --git a/tenant/http_client_urm.go b/tenant/http_client_urm.go index 25c4d2d1203..3b094d45b53 100644 --- a/tenant/http_client_urm.go +++ b/tenant/http_client_urm.go @@ -4,6 +4,8 @@ import ( "context" "path" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/pkg/httpc" ) @@ -49,7 +51,7 @@ func (s *UserResourceMappingClient) FindUserResourceMappings(ctx context.Context } // DeleteUserResourceMapping will delete user resource mapping based in criteria. -func (s *UserResourceMappingClient) DeleteUserResourceMapping(ctx context.Context, resourceID influxdb.ID, userID influxdb.ID) error { +func (s *UserResourceMappingClient) DeleteUserResourceMapping(ctx context.Context, resourceID platform.ID, userID platform.ID) error { urlPath := resourceIDUserPath(influxdb.OrgsResourceType, resourceID, influxdb.Member, userID) return s.Client. Delete(urlPath). @@ -111,17 +113,17 @@ func (s *SpecificURMSvc) CreateUserResourceMapping(ctx context.Context, m *influ } // DeleteUserResourceMapping will delete user resource mapping based in criteria. -func (s *SpecificURMSvc) DeleteUserResourceMapping(ctx context.Context, resourceID influxdb.ID, userID influxdb.ID) error { +func (s *SpecificURMSvc) DeleteUserResourceMapping(ctx context.Context, resourceID platform.ID, userID platform.ID) error { urlPath := resourceIDUserPath(s.rt, resourceID, s.ut, userID) return s.Client. Delete(urlPath). Do(ctx) } -func resourceIDPath(resourceType influxdb.ResourceType, resourceID influxdb.ID, p string) string { +func resourceIDPath(resourceType influxdb.ResourceType, resourceID platform.ID, p string) string { return path.Join("/api/v2/", string(resourceType), resourceID.String(), p) } -func resourceIDUserPath(resourceType influxdb.ResourceType, resourceID influxdb.ID, userType influxdb.UserType, userID influxdb.ID) string { +func resourceIDUserPath(resourceType influxdb.ResourceType, resourceID platform.ID, userType influxdb.UserType, userID platform.ID) string { return path.Join("/api/v2/", string(resourceType), resourceID.String(), string(userType)+"s", userID.String()) } diff --git a/tenant/http_client_user.go b/tenant/http_client_user.go index cc024fb53b0..ceb5caa0068 100644 --- a/tenant/http_client_user.go +++ b/tenant/http_client_user.go @@ -4,6 +4,9 @@ import ( "context" "net/http" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" khttp "github.com/influxdata/influxdb/v2/kit/transport/http" "github.com/influxdata/influxdb/v2/pkg/httpc" @@ -17,7 +20,7 @@ type UserClientService struct { } // FindMe returns user information about the owner of the token -func (s *UserClientService) FindMe(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { +func (s *UserClientService) FindMe(ctx context.Context, id platform.ID) (*influxdb.User, error) { var res UserResponse err := s.Client. Get(prefixMe). @@ -30,7 +33,7 @@ func (s *UserClientService) FindMe(ctx context.Context, id influxdb.ID) (*influx } // FindUserByID returns a single user by ID. -func (s *UserClientService) FindUserByID(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { +func (s *UserClientService) FindUserByID(ctx context.Context, id platform.ID) (*influxdb.User, error) { var res UserResponse err := s.Client. Get(prefixUsers, id.String()). @@ -45,22 +48,22 @@ func (s *UserClientService) FindUserByID(ctx context.Context, id influxdb.ID) (* // FindUser returns the first user that matches filter. func (s *UserClientService) FindUser(ctx context.Context, filter influxdb.UserFilter) (*influxdb.User, error) { if filter.ID == nil && filter.Name == nil { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: "user not found", } } users, n, err := s.FindUsers(ctx, filter) if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Op: s.OpPrefix + influxdb.OpFindUser, Err: err, } } if n == 0 { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Op: s.OpPrefix + influxdb.OpFindUser, Msg: "no results found", } @@ -104,7 +107,7 @@ func (s *UserClientService) CreateUser(ctx context.Context, u *influxdb.User) er // UpdateUser updates a single user with changeset. // Returns the new user state after update. -func (s *UserClientService) UpdateUser(ctx context.Context, id influxdb.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { +func (s *UserClientService) UpdateUser(ctx context.Context, id platform.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { var res UserResponse err := s.Client. PatchJSON(upd, prefixUsers, id.String()). @@ -117,7 +120,7 @@ func (s *UserClientService) UpdateUser(ctx context.Context, id influxdb.ID, upd } // DeleteUser removes a user by ID. -func (s *UserClientService) DeleteUser(ctx context.Context, id influxdb.ID) error { +func (s *UserClientService) DeleteUser(ctx context.Context, id platform.ID) error { return s.Client. Delete(prefixUsers, id.String()). StatusFn(func(resp *http.Response) error { @@ -127,7 +130,7 @@ func (s *UserClientService) DeleteUser(ctx context.Context, id influxdb.ID) erro } // FindUserByID returns a single user by ID. -func (s *UserClientService) FindPermissionForUser(ctx context.Context, id influxdb.ID) (influxdb.PermissionSet, error) { +func (s *UserClientService) FindPermissionForUser(ctx context.Context, id platform.ID) (influxdb.PermissionSet, error) { var ps influxdb.PermissionSet err := s.Client. Get(prefixUsers, id.String(), "permissions"). @@ -147,7 +150,7 @@ type PasswordClientService struct { var _ influxdb.PasswordsService = (*PasswordClientService)(nil) // SetPassword sets the user's password. -func (s *PasswordClientService) SetPassword(ctx context.Context, userID influxdb.ID, password string) error { +func (s *PasswordClientService) SetPassword(ctx context.Context, userID platform.ID, password string) error { return s.Client. PostJSON(passwordSetRequest{ Password: password, @@ -156,12 +159,12 @@ func (s *PasswordClientService) SetPassword(ctx context.Context, userID influxdb } // ComparePassword compares the user new password with existing. Note: is not implemented. -func (s *PasswordClientService) ComparePassword(ctx context.Context, userID influxdb.ID, password string) error { +func (s *PasswordClientService) ComparePassword(ctx context.Context, userID platform.ID, password string) error { panic("not implemented") } // CompareAndSetPassword compares the old and new password and submits the new password if possible. // Note: is not implemented. -func (s *PasswordClientService) CompareAndSetPassword(ctx context.Context, userID influxdb.ID, old string, new string) error { +func (s *PasswordClientService) CompareAndSetPassword(ctx context.Context, userID platform.ID, old string, new string) error { panic("not implemented") } diff --git a/tenant/http_handler_urm.go b/tenant/http_handler_urm.go index 9e883e7a901..efb1b4666cb 100644 --- a/tenant/http_handler_urm.go +++ b/tenant/http_handler_urm.go @@ -7,6 +7,9 @@ import ( "net/http" "path" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" "github.com/influxdata/influxdb/v2" kithttp "github.com/influxdata/influxdb/v2/kit/transport/http" @@ -83,19 +86,19 @@ func (h *urmHandler) getURMsByType(w http.ResponseWriter, r *http.Request) { } type getRequest struct { - ResourceID influxdb.ID + ResourceID platform.ID } func (h *urmHandler) decodeGetRequest(ctx context.Context, r *http.Request) (*getRequest, error) { id := chi.URLParam(r, h.idLookupKey) if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -138,20 +141,20 @@ func (h *urmHandler) postURMByType(w http.ResponseWriter, r *http.Request) { } type postRequest struct { - UserID influxdb.ID - ResourceID influxdb.ID + UserID platform.ID + ResourceID platform.ID } func (h urmHandler) decodePostRequest(ctx context.Context, r *http.Request) (*postRequest, error) { id := chi.URLParam(r, h.idLookupKey) if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var rid influxdb.ID + var rid platform.ID if err := rid.DecodeFromString(id); err != nil { return nil, err } @@ -162,8 +165,8 @@ func (h urmHandler) decodePostRequest(ctx context.Context, r *http.Request) (*po } if !u.ID.Valid() { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "user id missing or invalid", } } @@ -192,33 +195,33 @@ func (h *urmHandler) deleteURM(w http.ResponseWriter, r *http.Request) { } type deleteRequest struct { - userID influxdb.ID - resourceID influxdb.ID + userID platform.ID + resourceID platform.ID } func (h *urmHandler) decodeDeleteRequest(ctx context.Context, r *http.Request) (*deleteRequest, error) { id := chi.URLParam(r, h.idLookupKey) if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var rid influxdb.ID + var rid platform.ID if err := rid.DecodeFromString(id); err != nil { return nil, err } id = chi.URLParam(r, "userID") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing member id", } } - var uid influxdb.ID + var uid platform.ID if err := uid.DecodeFromString(id); err != nil { return nil, err } diff --git a/tenant/http_handler_urm_test.go b/tenant/http_handler_urm_test.go index 0834235a5a3..0af3f1e3dfb 100644 --- a/tenant/http_handler_urm_test.go +++ b/tenant/http_handler_urm_test.go @@ -5,6 +5,7 @@ import ( "context" "encoding/json" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" "io/ioutil" "net/http" "net/http/httptest" @@ -45,7 +46,7 @@ func TestUserResourceMappingService_GetMembersHandler(t *testing.T) { name: "get members", fields: fields{ userService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ID: id, Name: fmt.Sprintf("user%s", id), Status: influxdb.Active}, nil }, }, @@ -108,7 +109,7 @@ func TestUserResourceMappingService_GetMembersHandler(t *testing.T) { name: "get owners", fields: fields{ userService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ID: id, Name: fmt.Sprintf("user%s", id), Status: influxdb.Active}, nil }, }, @@ -243,7 +244,7 @@ func TestUserResourceMappingService_PostMembersHandler(t *testing.T) { name: "post members", fields: fields{ userService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ID: id, Name: fmt.Sprintf("user%s", id), Status: influxdb.Active}, nil }, }, @@ -281,7 +282,7 @@ func TestUserResourceMappingService_PostMembersHandler(t *testing.T) { name: "post owners", fields: fields{ userService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ID: id, Name: fmt.Sprintf("user%s", id), Status: influxdb.Active}, nil }, }, @@ -391,7 +392,7 @@ func TestUserResourceMappingService_Client(t *testing.T) { name: "post members", fields: fields{ userService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ID: id, Name: fmt.Sprintf("user%s", id), Status: influxdb.Active}, nil }, }, @@ -419,7 +420,7 @@ func TestUserResourceMappingService_Client(t *testing.T) { name: "post owners", fields: fields{ userService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ID: id, Name: fmt.Sprintf("user%s", id), Status: influxdb.Active}, nil }, }, diff --git a/tenant/http_server_bucket.go b/tenant/http_server_bucket.go index 6fc5f4a5098..e9d8dd464de 100644 --- a/tenant/http_server_bucket.go +++ b/tenant/http_server_bucket.go @@ -6,6 +6,9 @@ import ( "net/http" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/influxdata/influxdb/v2" @@ -70,8 +73,8 @@ func (h *BucketHandler) Prefix() string { // bucket is used for serialization/deserialization with duration string syntax. type bucket struct { - ID influxdb.ID `json:"id,omitempty"` - OrgID influxdb.ID `json:"orgID,omitempty"` + ID platform.ID `json:"id,omitempty"` + OrgID platform.ID `json:"orgID,omitempty"` Type string `json:"type"` Description string `json:"description,omitempty"` Name string `json:"name"` @@ -152,8 +155,8 @@ type bucketUpdate struct { func (b *bucketUpdate) OK() error { if len(b.RetentionRules) > 1 { - return &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + return &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: "buckets cannot have more than one retention rule at this time", } } @@ -161,14 +164,14 @@ func (b *bucketUpdate) OK() error { if len(b.RetentionRules) > 0 { rule := b.RetentionRules[0] if rule.EverySeconds != nil && *rule.EverySeconds < 0 { - return &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + return &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: "expiration seconds cannot be negative", } } if rule.ShardGroupDurationSeconds != nil && *rule.ShardGroupDurationSeconds < 0 { - return &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + return &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: "shard-group duration seconds cannot be negative", } } @@ -303,7 +306,7 @@ func (h *BucketHandler) handlePostBucket(w http.ResponseWriter, r *http.Request) } type postBucketRequest struct { - OrgID influxdb.ID `json:"orgID,omitempty"` + OrgID platform.ID `json:"orgID,omitempty"` Name string `json:"name"` Description string `json:"description"` RetentionPolicyName string `json:"rp,omitempty"` // This to support v1 sources @@ -312,15 +315,15 @@ type postBucketRequest struct { func (b *postBucketRequest) OK() error { if !b.OrgID.Valid() { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "organization id must be provided", } } if len(b.RetentionRules) > 1 { - return &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + return &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: "buckets cannot have more than one retention rule at this time", } } @@ -329,14 +332,14 @@ func (b *postBucketRequest) OK() error { rule := b.RetentionRules[0] if rule.EverySeconds < 0 { - return &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + return &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: "expiration seconds cannot be negative", } } if rule.ShardGroupDurationSeconds < 0 { - return &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + return &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: "shard-group duration seconds cannot be negative", } } @@ -370,7 +373,7 @@ func (b postBucketRequest) toInfluxDB() *influxdb.Bucket { func (h *BucketHandler) handleGetBucket(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - id, err := influxdb.IDFromString(chi.URLParam(r, "id")) + id, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { h.api.Err(w, r, err) return @@ -393,7 +396,7 @@ func (h *BucketHandler) handleGetBucket(w http.ResponseWriter, r *http.Request) // handleDeleteBucket is the HTTP handler for the DELETE /api/v2/buckets/:id route. func (h *BucketHandler) handleDeleteBucket(w http.ResponseWriter, r *http.Request) { - id, err := influxdb.IDFromString(chi.URLParam(r, "id")) + id, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { h.api.Err(w, r, err) return @@ -444,7 +447,7 @@ func decodeGetBucketsRequest(r *http.Request) (*getBucketsRequest, error) { req.opts = *opts if orgID := qp.Get("orgID"); orgID != "" { - id, err := influxdb.IDFromString(orgID) + id, err := platform.IDFromString(orgID) if err != nil { return nil, err } @@ -460,7 +463,7 @@ func decodeGetBucketsRequest(r *http.Request) (*getBucketsRequest, error) { } if bucketID := qp.Get("id"); bucketID != "" { - id, err := influxdb.IDFromString(bucketID) + id, err := platform.IDFromString(bucketID) if err != nil { return nil, err } @@ -472,7 +475,7 @@ func decodeGetBucketsRequest(r *http.Request) (*getBucketsRequest, error) { // handlePatchBucket is the HTTP handler for the PATCH /api/v2/buckets route. func (h *BucketHandler) handlePatchBucket(w http.ResponseWriter, r *http.Request) { - id, err := influxdb.IDFromString(chi.URLParam(r, "id")) + id, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { h.api.Err(w, r, err) return @@ -504,7 +507,7 @@ func (h *BucketHandler) handlePatchBucket(w http.ResponseWriter, r *http.Request h.api.Respond(w, r, http.StatusOK, NewBucketResponse(b)) } -func (h *BucketHandler) lookupOrgByBucketID(ctx context.Context, id influxdb.ID) (influxdb.ID, error) { +func (h *BucketHandler) lookupOrgByBucketID(ctx context.Context, id platform.ID) (platform.ID, error) { b, err := h.bucketSvc.FindBucketByID(ctx, id) if err != nil { return 0, err diff --git a/tenant/http_server_bucket_test.go b/tenant/http_server_bucket_test.go index bf2d051ac04..dff65c8e9a0 100644 --- a/tenant/http_server_bucket_test.go +++ b/tenant/http_server_bucket_test.go @@ -2,6 +2,8 @@ package tenant_test import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "net/http/httptest" "testing" "time" @@ -83,12 +85,12 @@ func TestHTTPBucketService(t *testing.T) { itesting.BucketService(initBucketHttpService, t) } -const idOne = influxdb.ID(iota + 1) +const idOne = platform.ID(iota + 1) func TestHTTPBucketService_InvalidRetention(t *testing.T) { type args struct { name string - id influxdb.ID + id platform.ID retention int shardDuration int description *string @@ -136,8 +138,8 @@ func TestHTTPBucketService_InvalidRetention(t *testing.T) { retention: -1, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + err: &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: "expiration seconds cannot be negative", }, }, @@ -174,8 +176,8 @@ func TestHTTPBucketService_InvalidRetention(t *testing.T) { shardDuration: -1, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EUnprocessableEntity, + err: &errors.Error{ + Code: errors.EUnprocessableEntity, Msg: "shard-group duration seconds cannot be negative", }, }, diff --git a/tenant/http_server_org.go b/tenant/http_server_org.go index c8ef3b6333b..cb83d422069 100644 --- a/tenant/http_server_org.go +++ b/tenant/http_server_org.go @@ -5,6 +5,8 @@ import ( "fmt" "net/http" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/influxdata/influxdb/v2" @@ -123,7 +125,7 @@ func (h *OrgHandler) handlePostOrg(w http.ResponseWriter, r *http.Request) { // handleGetOrg is the HTTP handler for the GET /api/v2/orgs/:id route. func (h *OrgHandler) handleGetOrg(w http.ResponseWriter, r *http.Request) { - id, err := influxdb.IDFromString(chi.URLParam(r, "id")) + id, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { h.api.Err(w, r, err) return @@ -155,14 +157,14 @@ func (h *OrgHandler) handleGetOrgs(w http.ResponseWriter, r *http.Request) { } if id := qp.Get("orgID"); id != "" { - i, err := influxdb.IDFromString(id) + i, err := platform.IDFromString(id) if err == nil { filter.ID = i } } if id := qp.Get("userID"); id != "" { - i, err := influxdb.IDFromString(id) + i, err := platform.IDFromString(id) if err == nil { filter.UserID = i } @@ -180,7 +182,7 @@ func (h *OrgHandler) handleGetOrgs(w http.ResponseWriter, r *http.Request) { // handlePatchOrg is the HTTP handler for the PATH /api/v2/orgs route. func (h *OrgHandler) handlePatchOrg(w http.ResponseWriter, r *http.Request) { - id, err := influxdb.IDFromString(chi.URLParam(r, "id")) + id, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { h.api.Err(w, r, err) return @@ -204,7 +206,7 @@ func (h *OrgHandler) handlePatchOrg(w http.ResponseWriter, r *http.Request) { // handleDeleteOrganization is the HTTP handler for the DELETE /api/v2/orgs/:id route. func (h *OrgHandler) handleDeleteOrg(w http.ResponseWriter, r *http.Request) { - id, err := influxdb.IDFromString(chi.URLParam(r, "id")) + id, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { h.api.Err(w, r, err) return @@ -220,7 +222,7 @@ func (h *OrgHandler) handleDeleteOrg(w http.ResponseWriter, r *http.Request) { h.api.Respond(w, r, http.StatusNoContent, nil) } -func (h *OrgHandler) lookupOrgByID(ctx context.Context, id influxdb.ID) (influxdb.ID, error) { +func (h *OrgHandler) lookupOrgByID(ctx context.Context, id platform.ID) (platform.ID, error) { _, err := h.orgSvc.FindOrganizationByID(ctx, id) if err != nil { return 0, err diff --git a/tenant/http_server_user.go b/tenant/http_server_user.go index 49ce656d616..f61b7798553 100644 --- a/tenant/http_server_user.go +++ b/tenant/http_server_user.go @@ -7,6 +7,9 @@ import ( "net/http" "strings" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/influxdata/influxdb/v2" @@ -90,17 +93,17 @@ func (h *UserHandler) handlePostUserPassword(w http.ResponseWriter, r *http.Requ var body passwordSetRequest err := json.NewDecoder(r.Body).Decode(&body) if err != nil { - h.api.Err(w, r, &influxdb.Error{ - Code: influxdb.EInvalid, + h.api.Err(w, r, &errors.Error{ + Code: errors.EInvalid, Err: err, }) return } param := chi.URLParam(r, "id") - userID, err := influxdb.IDFromString(param) + userID, err := platform.IDFromString(param) if err != nil { - h.api.Err(w, r, &influxdb.Error{ + h.api.Err(w, r, &errors.Error{ Msg: "invalid user ID provided in route", }) return @@ -122,9 +125,9 @@ func (h *UserHandler) putPassword(ctx context.Context, w http.ResponseWriter, r } param := chi.URLParam(r, "id") - userID, err := influxdb.IDFromString(param) + userID, err := platform.IDFromString(param) if err != nil { - h.api.Err(w, r, &influxdb.Error{ + h.api.Err(w, r, &errors.Error{ Msg: "invalid user ID provided in route", }) return @@ -168,8 +171,8 @@ func decodePasswordResetRequest(r *http.Request) (*passwordResetRequest, error) pr := new(passwordResetRequestBody) err := json.NewDecoder(r.Body).Decode(pr) if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -261,14 +264,14 @@ func (h *UserHandler) handleGetUser(w http.ResponseWriter, r *http.Request) { func (h *UserHandler) handleGetPermissions(w http.ResponseWriter, r *http.Request) { id := chi.URLParam(r, "id") if id == "" { - err := &influxdb.Error{ - Code: influxdb.EInvalid, + err := &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } h.api.Err(w, r, err) return } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { h.api.Err(w, r, err) return @@ -284,19 +287,19 @@ func (h *UserHandler) handleGetPermissions(w http.ResponseWriter, r *http.Reques } type getUserRequest struct { - UserID influxdb.ID + UserID platform.ID } func decodeGetUserRequest(ctx context.Context, r *http.Request) (*getUserRequest, error) { id := chi.URLParam(r, "id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -327,19 +330,19 @@ func (h *UserHandler) handleDeleteUser(w http.ResponseWriter, r *http.Request) { } type deleteUserRequest struct { - UserID influxdb.ID + UserID platform.ID } func decodeDeleteUserRequest(ctx context.Context, r *http.Request) (*deleteUserRequest, error) { id := chi.URLParam(r, "id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } @@ -425,7 +428,7 @@ func decodeGetUsersRequest(ctx context.Context, r *http.Request) (*getUsersReque req := &getUsersRequest{} if userID := qp.Get("id"); userID != "" { - id, err := influxdb.IDFromString(userID) + id, err := platform.IDFromString(userID) if err != nil { return nil, err } @@ -460,19 +463,19 @@ func (h *UserHandler) handlePatchUser(w http.ResponseWriter, r *http.Request) { type patchUserRequest struct { Update influxdb.UserUpdate - UserID influxdb.ID + UserID platform.ID } func decodePatchUserRequest(ctx context.Context, r *http.Request) (*patchUserRequest, error) { id := chi.URLParam(r, "id") if id == "" { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "url missing id", } } - var i influxdb.ID + var i platform.ID if err := i.DecodeFromString(id); err != nil { return nil, err } diff --git a/tenant/middleware_bucket_auth.go b/tenant/middleware_bucket_auth.go index 97471e4b9bb..08cc89f5075 100644 --- a/tenant/middleware_bucket_auth.go +++ b/tenant/middleware_bucket_auth.go @@ -3,6 +3,8 @@ package tenant import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/authorizer" "github.com/influxdata/influxdb/v2/kit/tracing" @@ -26,7 +28,7 @@ func NewAuthedBucketService(s influxdb.BucketService) *AuthedBucketService { } // FindBucketByID checks to see if the authorizer on context has read access to the id provided. -func (s *AuthedBucketService) FindBucketByID(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { +func (s *AuthedBucketService) FindBucketByID(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -41,7 +43,7 @@ func (s *AuthedBucketService) FindBucketByID(ctx context.Context, id influxdb.ID } // FindBucketByName returns a bucket by name for a particular organization. -func (s *AuthedBucketService) FindBucketByName(ctx context.Context, orgID influxdb.ID, n string) (*influxdb.Bucket, error) { +func (s *AuthedBucketService) FindBucketByName(ctx context.Context, orgID platform.ID, n string) (*influxdb.Bucket, error) { span, ctx := tracing.StartSpanFromContext(ctx) defer span.Finish() @@ -96,7 +98,7 @@ func (s *AuthedBucketService) CreateBucket(ctx context.Context, b *influxdb.Buck } // UpdateBucket checks to see if the authorizer on context has write access to the bucket provided. -func (s *AuthedBucketService) UpdateBucket(ctx context.Context, id influxdb.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { +func (s *AuthedBucketService) UpdateBucket(ctx context.Context, id platform.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { b, err := s.s.FindBucketByID(ctx, id) if err != nil { return nil, err @@ -108,7 +110,7 @@ func (s *AuthedBucketService) UpdateBucket(ctx context.Context, id influxdb.ID, } // DeleteBucket checks to see if the authorizer on context has write access to the bucket provided. -func (s *AuthedBucketService) DeleteBucket(ctx context.Context, id influxdb.ID) error { +func (s *AuthedBucketService) DeleteBucket(ctx context.Context, id platform.ID) error { b, err := s.s.FindBucketByID(ctx, id) if err != nil { return err diff --git a/tenant/middleware_bucket_auth_test.go b/tenant/middleware_bucket_auth_test.go index ec3de1b950c..9fce1863d74 100644 --- a/tenant/middleware_bucket_auth_test.go +++ b/tenant/middleware_bucket_auth_test.go @@ -3,6 +3,8 @@ package tenant_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "sort" "testing" @@ -33,7 +35,7 @@ func TestBucketService_FindBucketByID(t *testing.T) { } type args struct { permission influxdb.Permission - id influxdb.ID + id platform.ID } type wants struct { err error @@ -49,7 +51,7 @@ func TestBucketService_FindBucketByID(t *testing.T) { name: "authorized to access id", fields: fields{ BucketService: &mock.BucketService{ - FindBucketByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: id, OrgID: 10, @@ -75,7 +77,7 @@ func TestBucketService_FindBucketByID(t *testing.T) { name: "unauthorized to access id", fields: fields{ BucketService: &mock.BucketService{ - FindBucketByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: id, OrgID: 10, @@ -94,9 +96,9 @@ func TestBucketService_FindBucketByID(t *testing.T) { id: 1, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/000000000000000a/buckets/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -179,9 +181,9 @@ func TestBucketService_FindBucket(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/000000000000000a/buckets/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -334,7 +336,7 @@ func TestBucketService_UpdateBucket(t *testing.T) { BucketService influxdb.BucketService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -351,13 +353,13 @@ func TestBucketService_UpdateBucket(t *testing.T) { name: "authorized to update bucket", fields: fields{ BucketService: &mock.BucketService{ - FindBucketByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: 1, OrgID: 10, }, nil }, - UpdateBucketFn: func(ctx context.Context, id influxdb.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { + UpdateBucketFn: func(ctx context.Context, id platform.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: 1, OrgID: 10, @@ -392,13 +394,13 @@ func TestBucketService_UpdateBucket(t *testing.T) { name: "unauthorized to update bucket", fields: fields{ BucketService: &mock.BucketService{ - FindBucketByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: 1, OrgID: 10, }, nil }, - UpdateBucketFn: func(ctx context.Context, id influxdb.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { + UpdateBucketFn: func(ctx context.Context, id platform.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: 1, OrgID: 10, @@ -419,9 +421,9 @@ func TestBucketService_UpdateBucket(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/buckets/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -445,7 +447,7 @@ func TestBucketService_DeleteBucket(t *testing.T) { BucketService influxdb.BucketService } type args struct { - id influxdb.ID + id platform.ID permissions []influxdb.Permission } type wants struct { @@ -462,13 +464,13 @@ func TestBucketService_DeleteBucket(t *testing.T) { name: "authorized to delete bucket", fields: fields{ BucketService: &mock.BucketService{ - FindBucketByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: 1, OrgID: 10, }, nil }, - DeleteBucketFn: func(ctx context.Context, id influxdb.ID) error { + DeleteBucketFn: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -500,13 +502,13 @@ func TestBucketService_DeleteBucket(t *testing.T) { name: "unauthorized to delete bucket", fields: fields{ BucketService: &mock.BucketService{ - FindBucketByIDFn: func(ctc context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctc context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: 1, OrgID: 10, }, nil }, - DeleteBucketFn: func(ctx context.Context, id influxdb.ID) error { + DeleteBucketFn: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -524,9 +526,9 @@ func TestBucketService_DeleteBucket(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/buckets/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -551,7 +553,7 @@ func TestBucketService_CreateBucket(t *testing.T) { } type args struct { permission influxdb.Permission - orgID influxdb.ID + orgID platform.ID } type wants struct { err error @@ -606,9 +608,9 @@ func TestBucketService_CreateBucket(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/000000000000000a/buckets is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, diff --git a/tenant/middleware_bucket_logging.go b/tenant/middleware_bucket_logging.go index bafff2c03e3..2cb561bba6f 100644 --- a/tenant/middleware_bucket_logging.go +++ b/tenant/middleware_bucket_logging.go @@ -5,6 +5,8 @@ import ( "fmt" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "go.uber.org/zap" ) @@ -36,7 +38,7 @@ func (l *BucketLogger) CreateBucket(ctx context.Context, u *influxdb.Bucket) (er return l.bucketService.CreateBucket(ctx, u) } -func (l *BucketLogger) FindBucketByID(ctx context.Context, id influxdb.ID) (u *influxdb.Bucket, err error) { +func (l *BucketLogger) FindBucketByID(ctx context.Context, id platform.ID) (u *influxdb.Bucket, err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -49,7 +51,7 @@ func (l *BucketLogger) FindBucketByID(ctx context.Context, id influxdb.ID) (u *i return l.bucketService.FindBucketByID(ctx, id) } -func (l *BucketLogger) FindBucketByName(ctx context.Context, orgID influxdb.ID, name string) (u *influxdb.Bucket, err error) { +func (l *BucketLogger) FindBucketByName(ctx context.Context, orgID platform.ID, name string) (u *influxdb.Bucket, err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -86,7 +88,7 @@ func (l *BucketLogger) FindBuckets(ctx context.Context, filter influxdb.BucketFi return l.bucketService.FindBuckets(ctx, filter, opt...) } -func (l *BucketLogger) UpdateBucket(ctx context.Context, id influxdb.ID, upd influxdb.BucketUpdate) (u *influxdb.Bucket, err error) { +func (l *BucketLogger) UpdateBucket(ctx context.Context, id platform.ID, upd influxdb.BucketUpdate) (u *influxdb.Bucket, err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -98,7 +100,7 @@ func (l *BucketLogger) UpdateBucket(ctx context.Context, id influxdb.ID, upd inf return l.bucketService.UpdateBucket(ctx, id, upd) } -func (l *BucketLogger) DeleteBucket(ctx context.Context, id influxdb.ID) (err error) { +func (l *BucketLogger) DeleteBucket(ctx context.Context, id platform.ID) (err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { diff --git a/tenant/middleware_bucket_metrics.go b/tenant/middleware_bucket_metrics.go index 88fecb44ac3..55888f44deb 100644 --- a/tenant/middleware_bucket_metrics.go +++ b/tenant/middleware_bucket_metrics.go @@ -3,6 +3,8 @@ package tenant import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/metric" "github.com/prometheus/client_golang/prometheus" @@ -27,7 +29,7 @@ func NewBucketMetrics(reg prometheus.Registerer, s influxdb.BucketService, opts } // Returns a single bucket by ID. -func (m *BucketMetrics) FindBucketByID(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { +func (m *BucketMetrics) FindBucketByID(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { rec := m.rec.Record("find_bucket_by_id") bucket, err := m.bucketService.FindBucketByID(ctx, id) return bucket, rec(err) @@ -55,21 +57,21 @@ func (m *BucketMetrics) CreateBucket(ctx context.Context, b *influxdb.Bucket) er } // Updates a single bucket with changeset and returns the new bucket state after update. -func (m *BucketMetrics) UpdateBucket(ctx context.Context, id influxdb.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { +func (m *BucketMetrics) UpdateBucket(ctx context.Context, id platform.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { rec := m.rec.Record("update_bucket") updatedBucket, err := m.bucketService.UpdateBucket(ctx, id, upd) return updatedBucket, rec(err) } // Removes a bucket by ID. -func (m *BucketMetrics) DeleteBucket(ctx context.Context, id influxdb.ID) error { +func (m *BucketMetrics) DeleteBucket(ctx context.Context, id platform.ID) error { rec := m.rec.Record("delete_bucket") err := m.bucketService.DeleteBucket(ctx, id) return rec(err) } // FindBucketByName finds a Bucket given its name and Organization ID -func (m *BucketMetrics) FindBucketByName(ctx context.Context, orgID influxdb.ID, name string) (*influxdb.Bucket, error) { +func (m *BucketMetrics) FindBucketByName(ctx context.Context, orgID platform.ID, name string) (*influxdb.Bucket, error) { rec := m.rec.Record("find_bucket_by_name") bucket, err := m.bucketService.FindBucketByName(ctx, orgID, name) return bucket, rec(err) diff --git a/tenant/middleware_org_auth.go b/tenant/middleware_org_auth.go index 35d3662d90c..99b50e5a645 100644 --- a/tenant/middleware_org_auth.go +++ b/tenant/middleware_org_auth.go @@ -3,6 +3,8 @@ package tenant import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/authorizer" icontext "github.com/influxdata/influxdb/v2/context" @@ -26,7 +28,7 @@ func NewAuthedOrgService(s influxdb.OrganizationService) *AuthedOrgService { } // FindOrganizationByID checks to see if the authorizer on context has read access to the id provided. -func (s *AuthedOrgService) FindOrganizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { +func (s *AuthedOrgService) FindOrganizationByID(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { if _, _, err := authorizer.AuthorizeReadOrg(ctx, id); err != nil { return nil, err } @@ -75,7 +77,7 @@ func (s *AuthedOrgService) CreateOrganization(ctx context.Context, o *influxdb.O } // UpdateOrganization checks to see if the authorizer on context has write access to the organization provided. -func (s *AuthedOrgService) UpdateOrganization(ctx context.Context, id influxdb.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { +func (s *AuthedOrgService) UpdateOrganization(ctx context.Context, id platform.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { if _, _, err := authorizer.AuthorizeWriteOrg(ctx, id); err != nil { return nil, err } @@ -83,7 +85,7 @@ func (s *AuthedOrgService) UpdateOrganization(ctx context.Context, id influxdb.I } // DeleteOrganization checks to see if the authorizer on context has write access to the organization provided. -func (s *AuthedOrgService) DeleteOrganization(ctx context.Context, id influxdb.ID) error { +func (s *AuthedOrgService) DeleteOrganization(ctx context.Context, id platform.ID) error { if _, _, err := authorizer.AuthorizeWriteOrg(ctx, id); err != nil { return err } diff --git a/tenant/middleware_org_auth_test.go b/tenant/middleware_org_auth_test.go index faf4333ddbc..8ef2a302509 100644 --- a/tenant/middleware_org_auth_test.go +++ b/tenant/middleware_org_auth_test.go @@ -3,6 +3,8 @@ package tenant_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "sort" "testing" @@ -33,7 +35,7 @@ func TestOrgService_FindOrganizationByID(t *testing.T) { } type args struct { permission influxdb.Permission - id influxdb.ID + id platform.ID } type wants struct { err error @@ -49,7 +51,7 @@ func TestOrgService_FindOrganizationByID(t *testing.T) { name: "authorized to access id", fields: fields{ OrgService: &mock.OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: id, }, nil @@ -74,7 +76,7 @@ func TestOrgService_FindOrganizationByID(t *testing.T) { name: "unauthorized to access id", fields: fields{ OrgService: &mock.OrganizationService{ - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: id, }, nil @@ -92,9 +94,9 @@ func TestOrgService_FindOrganizationByID(t *testing.T) { id: 1, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -175,9 +177,9 @@ func TestOrgService_FindOrganization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:orgs/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -315,7 +317,7 @@ func TestOrgService_UpdateOrganization(t *testing.T) { OrgService influxdb.OrganizationService } type args struct { - id influxdb.ID + id platform.ID permission influxdb.Permission } type wants struct { @@ -332,7 +334,7 @@ func TestOrgService_UpdateOrganization(t *testing.T) { name: "authorized to update org", fields: fields{ OrgService: &mock.OrganizationService{ - UpdateOrganizationF: func(ctx context.Context, id influxdb.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { + UpdateOrganizationF: func(ctx context.Context, id platform.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: 1, }, nil @@ -357,7 +359,7 @@ func TestOrgService_UpdateOrganization(t *testing.T) { name: "unauthorized to update org", fields: fields{ OrgService: &mock.OrganizationService{ - UpdateOrganizationF: func(ctx context.Context, id influxdb.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { + UpdateOrganizationF: func(ctx context.Context, id platform.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: 1, }, nil @@ -375,9 +377,9 @@ func TestOrgService_UpdateOrganization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -401,7 +403,7 @@ func TestOrgService_DeleteOrganization(t *testing.T) { OrgService influxdb.OrganizationService } type args struct { - id influxdb.ID + id platform.ID permission influxdb.Permission } type wants struct { @@ -418,7 +420,7 @@ func TestOrgService_DeleteOrganization(t *testing.T) { name: "authorized to delete org", fields: fields{ OrgService: &mock.OrganizationService{ - DeleteOrganizationF: func(ctx context.Context, id influxdb.ID) error { + DeleteOrganizationF: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -441,7 +443,7 @@ func TestOrgService_DeleteOrganization(t *testing.T) { name: "unauthorized to delete org", fields: fields{ OrgService: &mock.OrganizationService{ - DeleteOrganizationF: func(ctx context.Context, id influxdb.ID) error { + DeleteOrganizationF: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -457,9 +459,9 @@ func TestOrgService_DeleteOrganization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -535,9 +537,9 @@ func TestOrgService_CreateOrganization(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:orgs is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, diff --git a/tenant/middleware_org_logging.go b/tenant/middleware_org_logging.go index ce708a791e3..cf88d257669 100644 --- a/tenant/middleware_org_logging.go +++ b/tenant/middleware_org_logging.go @@ -5,6 +5,8 @@ import ( "fmt" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "go.uber.org/zap" ) @@ -36,7 +38,7 @@ func (l *OrgLogger) CreateOrganization(ctx context.Context, u *influxdb.Organiza return l.orgService.CreateOrganization(ctx, u) } -func (l *OrgLogger) FindOrganizationByID(ctx context.Context, id influxdb.ID) (u *influxdb.Organization, err error) { +func (l *OrgLogger) FindOrganizationByID(ctx context.Context, id platform.ID) (u *influxdb.Organization, err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -74,7 +76,7 @@ func (l *OrgLogger) FindOrganizations(ctx context.Context, filter influxdb.Organ return l.orgService.FindOrganizations(ctx, filter, opt...) } -func (l *OrgLogger) UpdateOrganization(ctx context.Context, id influxdb.ID, upd influxdb.OrganizationUpdate) (u *influxdb.Organization, err error) { +func (l *OrgLogger) UpdateOrganization(ctx context.Context, id platform.ID, upd influxdb.OrganizationUpdate) (u *influxdb.Organization, err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -86,7 +88,7 @@ func (l *OrgLogger) UpdateOrganization(ctx context.Context, id influxdb.ID, upd return l.orgService.UpdateOrganization(ctx, id, upd) } -func (l *OrgLogger) DeleteOrganization(ctx context.Context, id influxdb.ID) (err error) { +func (l *OrgLogger) DeleteOrganization(ctx context.Context, id platform.ID) (err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { diff --git a/tenant/middleware_org_metrics.go b/tenant/middleware_org_metrics.go index a0b108f1161..87d72c5aca2 100644 --- a/tenant/middleware_org_metrics.go +++ b/tenant/middleware_org_metrics.go @@ -3,6 +3,8 @@ package tenant import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/metric" "github.com/prometheus/client_golang/prometheus" @@ -26,7 +28,7 @@ func NewOrgMetrics(reg prometheus.Registerer, s influxdb.OrganizationService, op } } -func (m *OrgMetrics) FindOrganizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { +func (m *OrgMetrics) FindOrganizationByID(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { rec := m.rec.Record("find_org_by_id") org, err := m.orgService.FindOrganizationByID(ctx, id) return org, rec(err) @@ -50,13 +52,13 @@ func (m *OrgMetrics) CreateOrganization(ctx context.Context, b *influxdb.Organiz return rec(err) } -func (m *OrgMetrics) UpdateOrganization(ctx context.Context, id influxdb.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { +func (m *OrgMetrics) UpdateOrganization(ctx context.Context, id platform.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { rec := m.rec.Record("update_org") updatedOrg, err := m.orgService.UpdateOrganization(ctx, id, upd) return updatedOrg, rec(err) } -func (m *OrgMetrics) DeleteOrganization(ctx context.Context, id influxdb.ID) error { +func (m *OrgMetrics) DeleteOrganization(ctx context.Context, id platform.ID) error { rec := m.rec.Record("delete_org") err := m.orgService.DeleteOrganization(ctx, id) return rec(err) diff --git a/tenant/middleware_urm_auth.go b/tenant/middleware_urm_auth.go index c24cee8fda1..fb038be06e6 100644 --- a/tenant/middleware_urm_auth.go +++ b/tenant/middleware_urm_auth.go @@ -3,6 +3,8 @@ package tenant import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/authorizer" kithttp "github.com/influxdata/influxdb/v2/kit/transport/http" @@ -67,7 +69,7 @@ func (s *AuthedURMService) CreateUserResourceMapping(ctx context.Context, m *inf return s.s.CreateUserResourceMapping(ctx, m) } -func (s *AuthedURMService) DeleteUserResourceMapping(ctx context.Context, resourceID influxdb.ID, userID influxdb.ID) error { +func (s *AuthedURMService) DeleteUserResourceMapping(ctx context.Context, resourceID platform.ID, userID platform.ID) error { if !resourceID.Valid() || !userID.Valid() { return ErrInvalidURMID } diff --git a/tenant/middleware_urm_auth_test.go b/tenant/middleware_urm_auth_test.go index b135568e089..c2ea35bc1be 100644 --- a/tenant/middleware_urm_auth_test.go +++ b/tenant/middleware_urm_auth_test.go @@ -4,6 +4,9 @@ import ( "context" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" influxdbcontext "github.com/influxdata/influxdb/v2/context" @@ -13,9 +16,9 @@ import ( influxdbtesting "github.com/influxdata/influxdb/v2/testing" ) -var idOne influxdb.ID = 1 -var idTwo influxdb.ID = 2 -var idThree influxdb.ID = 3 +var idOne platform.ID = 1 +var idTwo platform.ID = 2 +var idThree platform.ID = 3 func TestURMService_FindUserResourceMappings(t *testing.T) { type fields struct { @@ -298,7 +301,7 @@ func TestURMService_WriteUserResourceMapping(t *testing.T) { CreateMappingFn: func(ctx context.Context, m *influxdb.UserResourceMapping) error { return nil }, - DeleteMappingFn: func(ctx context.Context, rid, uid influxdb.ID) error { + DeleteMappingFn: func(ctx context.Context, rid, uid platform.ID) error { return nil }, FindMappingsFn: func(ctx context.Context, filter influxdb.UserResourceMappingFilter) ([]*influxdb.UserResourceMapping, int, error) { @@ -333,7 +336,7 @@ func TestURMService_WriteUserResourceMapping(t *testing.T) { CreateMappingFn: func(ctx context.Context, m *influxdb.UserResourceMapping) error { return nil }, - DeleteMappingFn: func(ctx context.Context, rid, uid influxdb.ID) error { + DeleteMappingFn: func(ctx context.Context, rid, uid platform.ID) error { return nil }, FindMappingsFn: func(ctx context.Context, filter influxdb.UserResourceMappingFilter) ([]*influxdb.UserResourceMapping, int, error) { @@ -357,9 +360,9 @@ func TestURMService_WriteUserResourceMapping(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:buckets/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, diff --git a/tenant/middleware_urm_logging.go b/tenant/middleware_urm_logging.go index c2c2f7ef86c..e9022e8726b 100644 --- a/tenant/middleware_urm_logging.go +++ b/tenant/middleware_urm_logging.go @@ -5,6 +5,8 @@ import ( "fmt" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "go.uber.org/zap" ) @@ -48,7 +50,7 @@ func (l *URMLogger) FindUserResourceMappings(ctx context.Context, filter influxd return l.urmService.FindUserResourceMappings(ctx, filter, opt...) } -func (l *URMLogger) DeleteUserResourceMapping(ctx context.Context, resourceID, userID influxdb.ID) (err error) { +func (l *URMLogger) DeleteUserResourceMapping(ctx context.Context, resourceID, userID platform.ID) (err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { diff --git a/tenant/middleware_urm_metrics.go b/tenant/middleware_urm_metrics.go index c65c9196d09..ad25923fdca 100644 --- a/tenant/middleware_urm_metrics.go +++ b/tenant/middleware_urm_metrics.go @@ -3,6 +3,8 @@ package tenant import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/metric" "github.com/prometheus/client_golang/prometheus" @@ -38,7 +40,7 @@ func (m *UrmMetrics) CreateUserResourceMapping(ctx context.Context, urm *influxd return rec(err) } -func (m *UrmMetrics) DeleteUserResourceMapping(ctx context.Context, resourceID, userID influxdb.ID) error { +func (m *UrmMetrics) DeleteUserResourceMapping(ctx context.Context, resourceID, userID platform.ID) error { rec := m.rec.Record("delete_urm") err := m.urmService.DeleteUserResourceMapping(ctx, resourceID, userID) return rec(err) diff --git a/tenant/middleware_user_auth.go b/tenant/middleware_user_auth.go index 6b4531a21ce..debc60ba5e0 100644 --- a/tenant/middleware_user_auth.go +++ b/tenant/middleware_user_auth.go @@ -3,6 +3,8 @@ package tenant import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/authorizer" ) @@ -25,7 +27,7 @@ func NewAuthedUserService(s influxdb.UserService) *AuthedUserService { } // FindUserByID checks to see if the authorizer on context has read access to the id provided. -func (s *AuthedUserService) FindUserByID(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { +func (s *AuthedUserService) FindUserByID(ctx context.Context, id platform.ID) (*influxdb.User, error) { if _, _, err := authorizer.AuthorizeReadResource(ctx, influxdb.UsersResourceType, id); err != nil { return nil, err } @@ -64,7 +66,7 @@ func (s *AuthedUserService) CreateUser(ctx context.Context, o *influxdb.User) er } // UpdateUser checks to see if the authorizer on context has write access to the user provided. -func (s *AuthedUserService) UpdateUser(ctx context.Context, id influxdb.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { +func (s *AuthedUserService) UpdateUser(ctx context.Context, id platform.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { if _, _, err := authorizer.AuthorizeWriteResource(ctx, influxdb.UsersResourceType, id); err != nil { return nil, err } @@ -72,14 +74,14 @@ func (s *AuthedUserService) UpdateUser(ctx context.Context, id influxdb.ID, upd } // DeleteUser checks to see if the authorizer on context has write access to the user provided. -func (s *AuthedUserService) DeleteUser(ctx context.Context, id influxdb.ID) error { +func (s *AuthedUserService) DeleteUser(ctx context.Context, id platform.ID) error { if _, _, err := authorizer.AuthorizeWriteResource(ctx, influxdb.UsersResourceType, id); err != nil { return err } return s.s.DeleteUser(ctx, id) } -func (s *AuthedUserService) FindPermissionForUser(ctx context.Context, id influxdb.ID) (influxdb.PermissionSet, error) { +func (s *AuthedUserService) FindPermissionForUser(ctx context.Context, id platform.ID) (influxdb.PermissionSet, error) { if _, _, err := authorizer.AuthorizeReadResource(ctx, influxdb.UsersResourceType, id); err != nil { return nil, err } @@ -97,7 +99,7 @@ func NewAuthedPasswordService(svc influxdb.PasswordsService) *AuthedPasswordServ } // SetPassword overrides the password of a known user. -func (s *AuthedPasswordService) SetPassword(ctx context.Context, userID influxdb.ID, password string) error { +func (s *AuthedPasswordService) SetPassword(ctx context.Context, userID platform.ID, password string) error { if _, _, err := authorizer.AuthorizeWriteResource(ctx, influxdb.UsersResourceType, userID); err != nil { return err } @@ -106,12 +108,12 @@ func (s *AuthedPasswordService) SetPassword(ctx context.Context, userID influxdb // ComparePassword checks if the password matches the password recorded. // Passwords that do not match return errors. -func (s *AuthedPasswordService) ComparePassword(ctx context.Context, userID influxdb.ID, password string) error { +func (s *AuthedPasswordService) ComparePassword(ctx context.Context, userID platform.ID, password string) error { panic("not implemented") } // CompareAndSetPassword checks the password and if they match // updates to the new password. -func (s *AuthedPasswordService) CompareAndSetPassword(ctx context.Context, userID influxdb.ID, old string, new string) error { +func (s *AuthedPasswordService) CompareAndSetPassword(ctx context.Context, userID platform.ID, old string, new string) error { panic("not implemented") } diff --git a/tenant/middleware_user_auth_test.go b/tenant/middleware_user_auth_test.go index bacde805538..fbc7c168253 100644 --- a/tenant/middleware_user_auth_test.go +++ b/tenant/middleware_user_auth_test.go @@ -3,6 +3,8 @@ package tenant_test import ( "bytes" "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "sort" "testing" @@ -35,7 +37,7 @@ func TestUserService_FindUserByID(t *testing.T) { } type args struct { permission influxdb.Permission - id influxdb.ID + id platform.ID } type wants struct { err error @@ -51,7 +53,7 @@ func TestUserService_FindUserByID(t *testing.T) { name: "authorized to access id", fields: fields{ UserService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ ID: id, }, nil @@ -76,7 +78,7 @@ func TestUserService_FindUserByID(t *testing.T) { name: "unauthorized to access id", fields: fields{ UserService: &mock.UserService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ ID: id, }, nil @@ -94,9 +96,9 @@ func TestUserService_FindUserByID(t *testing.T) { id: 1, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:users/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -177,9 +179,9 @@ func TestUserService_FindUser(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "read:users/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -317,7 +319,7 @@ func TestUserService_UpdateUser(t *testing.T) { UserService influxdb.UserService } type args struct { - id influxdb.ID + id platform.ID permission influxdb.Permission } type wants struct { @@ -334,7 +336,7 @@ func TestUserService_UpdateUser(t *testing.T) { name: "authorized to update user", fields: fields{ UserService: &mock.UserService{ - UpdateUserFn: func(ctx context.Context, id influxdb.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { + UpdateUserFn: func(ctx context.Context, id platform.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { return &influxdb.User{ ID: 1, }, nil @@ -359,7 +361,7 @@ func TestUserService_UpdateUser(t *testing.T) { name: "unauthorized to update user", fields: fields{ UserService: &mock.UserService{ - UpdateUserFn: func(ctx context.Context, id influxdb.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { + UpdateUserFn: func(ctx context.Context, id platform.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { return &influxdb.User{ ID: 1, }, nil @@ -377,9 +379,9 @@ func TestUserService_UpdateUser(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:users/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -403,7 +405,7 @@ func TestUserService_DeleteUser(t *testing.T) { UserService influxdb.UserService } type args struct { - id influxdb.ID + id platform.ID permission influxdb.Permission } type wants struct { @@ -420,7 +422,7 @@ func TestUserService_DeleteUser(t *testing.T) { name: "authorized to delete user", fields: fields{ UserService: &mock.UserService{ - DeleteUserFn: func(ctx context.Context, id influxdb.ID) error { + DeleteUserFn: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -443,7 +445,7 @@ func TestUserService_DeleteUser(t *testing.T) { name: "unauthorized to delete user", fields: fields{ UserService: &mock.UserService{ - DeleteUserFn: func(ctx context.Context, id influxdb.ID) error { + DeleteUserFn: func(ctx context.Context, id platform.ID) error { return nil }, }, @@ -459,9 +461,9 @@ func TestUserService_DeleteUser(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:users/0000000000000001 is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -537,9 +539,9 @@ func TestUserService_CreateUser(t *testing.T) { }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Msg: "write:users is unauthorized", - Code: influxdb.EUnauthorized, + Code: errors.EUnauthorized, }, }, }, @@ -561,7 +563,7 @@ func TestUserService_CreateUser(t *testing.T) { func TestPasswordService(t *testing.T) { t.Run("SetPassword", func(t *testing.T) { t.Run("user with permissions should proceed", func(t *testing.T) { - userID := influxdb.ID(1) + userID := platform.ID(1) permission := influxdb.Permission{ Action: influxdb.WriteAction, @@ -572,7 +574,7 @@ func TestPasswordService(t *testing.T) { } fakeSVC := mock.NewPasswordsService() - fakeSVC.SetPasswordFn = func(_ context.Context, _ influxdb.ID, _ string) error { + fakeSVC.SetPasswordFn = func(_ context.Context, _ platform.ID, _ string) error { return nil } s := tenant.NewAuthedPasswordService(fakeSVC) @@ -584,8 +586,8 @@ func TestPasswordService(t *testing.T) { }) t.Run("user without permissions should proceed", func(t *testing.T) { - goodUserID := influxdb.ID(1) - badUserID := influxdb.ID(3) + goodUserID := platform.ID(1) + badUserID := platform.ID(3) tests := []struct { name string @@ -629,7 +631,7 @@ func TestPasswordService(t *testing.T) { for _, tt := range tests { fn := func(t *testing.T) { fakeSVC := &mock.PasswordsService{ - SetPasswordFn: func(_ context.Context, _ influxdb.ID, _ string) error { + SetPasswordFn: func(_ context.Context, _ platform.ID, _ string) error { return nil }, } diff --git a/tenant/middleware_user_logging.go b/tenant/middleware_user_logging.go index b72994f418f..5a1a755578b 100644 --- a/tenant/middleware_user_logging.go +++ b/tenant/middleware_user_logging.go @@ -5,6 +5,8 @@ import ( "fmt" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "go.uber.org/zap" ) @@ -37,7 +39,7 @@ func (l *UserLogger) CreateUser(ctx context.Context, u *influxdb.User) (err erro return l.userService.CreateUser(ctx, u) } -func (l *UserLogger) FindUserByID(ctx context.Context, id influxdb.ID) (u *influxdb.User, err error) { +func (l *UserLogger) FindUserByID(ctx context.Context, id platform.ID) (u *influxdb.User, err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -74,7 +76,7 @@ func (l *UserLogger) FindUsers(ctx context.Context, filter influxdb.UserFilter, return l.userService.FindUsers(ctx, filter, opt...) } -func (l *UserLogger) UpdateUser(ctx context.Context, id influxdb.ID, upd influxdb.UserUpdate) (u *influxdb.User, err error) { +func (l *UserLogger) UpdateUser(ctx context.Context, id platform.ID, upd influxdb.UserUpdate) (u *influxdb.User, err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -86,7 +88,7 @@ func (l *UserLogger) UpdateUser(ctx context.Context, id influxdb.ID, upd influxd return l.userService.UpdateUser(ctx, id, upd) } -func (l *UserLogger) DeleteUser(ctx context.Context, id influxdb.ID) (err error) { +func (l *UserLogger) DeleteUser(ctx context.Context, id platform.ID) (err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -99,7 +101,7 @@ func (l *UserLogger) DeleteUser(ctx context.Context, id influxdb.ID) (err error) return l.userService.DeleteUser(ctx, id) } -func (l *UserLogger) FindPermissionForUser(ctx context.Context, id influxdb.ID) (ps influxdb.PermissionSet, err error) { +func (l *UserLogger) FindPermissionForUser(ctx context.Context, id platform.ID) (ps influxdb.PermissionSet, err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -125,7 +127,7 @@ func NewPasswordLogger(log *zap.Logger, s influxdb.PasswordsService) *PasswordLo } } -func (l *PasswordLogger) SetPassword(ctx context.Context, userID influxdb.ID, password string) (err error) { +func (l *PasswordLogger) SetPassword(ctx context.Context, userID platform.ID, password string) (err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -138,7 +140,7 @@ func (l *PasswordLogger) SetPassword(ctx context.Context, userID influxdb.ID, pa return l.pwdService.SetPassword(ctx, userID, password) } -func (l *PasswordLogger) ComparePassword(ctx context.Context, userID influxdb.ID, password string) (err error) { +func (l *PasswordLogger) ComparePassword(ctx context.Context, userID platform.ID, password string) (err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { @@ -151,7 +153,7 @@ func (l *PasswordLogger) ComparePassword(ctx context.Context, userID influxdb.ID return l.pwdService.ComparePassword(ctx, userID, password) } -func (l *PasswordLogger) CompareAndSetPassword(ctx context.Context, userID influxdb.ID, old, new string) (err error) { +func (l *PasswordLogger) CompareAndSetPassword(ctx context.Context, userID platform.ID, old, new string) (err error) { defer func(start time.Time) { dur := zap.Duration("took", time.Since(start)) if err != nil { diff --git a/tenant/middleware_user_metrics.go b/tenant/middleware_user_metrics.go index 11cfce0cae5..a2753fc17af 100644 --- a/tenant/middleware_user_metrics.go +++ b/tenant/middleware_user_metrics.go @@ -3,6 +3,8 @@ package tenant import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kit/metric" "github.com/prometheus/client_golang/prometheus" @@ -27,7 +29,7 @@ func NewUserMetrics(reg prometheus.Registerer, s influxdb.UserService, opts ...m } } -func (m *UserMetrics) FindUserByID(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { +func (m *UserMetrics) FindUserByID(ctx context.Context, id platform.ID) (*influxdb.User, error) { rec := m.rec.Record("find_user_by_id") user, err := m.userService.FindUserByID(ctx, id) return user, rec(err) @@ -51,19 +53,19 @@ func (m *UserMetrics) CreateUser(ctx context.Context, u *influxdb.User) error { return rec(err) } -func (m *UserMetrics) UpdateUser(ctx context.Context, id influxdb.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { +func (m *UserMetrics) UpdateUser(ctx context.Context, id platform.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { rec := m.rec.Record("update_user") updatedUser, err := m.userService.UpdateUser(ctx, id, upd) return updatedUser, rec(err) } -func (m *UserMetrics) DeleteUser(ctx context.Context, id influxdb.ID) error { +func (m *UserMetrics) DeleteUser(ctx context.Context, id platform.ID) error { rec := m.rec.Record("delete_user") err := m.userService.DeleteUser(ctx, id) return rec(err) } -func (m *UserMetrics) FindPermissionForUser(ctx context.Context, id influxdb.ID) (influxdb.PermissionSet, error) { +func (m *UserMetrics) FindPermissionForUser(ctx context.Context, id platform.ID) (influxdb.PermissionSet, error) { rec := m.rec.Record("find_permission_for_user") ps, err := m.userService.FindPermissionForUser(ctx, id) return ps, rec(err) @@ -85,19 +87,19 @@ func NewPasswordMetrics(reg prometheus.Registerer, s influxdb.PasswordsService, } } -func (m *PasswordMetrics) SetPassword(ctx context.Context, userID influxdb.ID, password string) error { +func (m *PasswordMetrics) SetPassword(ctx context.Context, userID platform.ID, password string) error { rec := m.rec.Record("set_password") err := m.pwdService.SetPassword(ctx, userID, password) return rec(err) } -func (m *PasswordMetrics) ComparePassword(ctx context.Context, userID influxdb.ID, password string) error { +func (m *PasswordMetrics) ComparePassword(ctx context.Context, userID platform.ID, password string) error { rec := m.rec.Record("compare_password") err := m.pwdService.ComparePassword(ctx, userID, password) return rec(err) } -func (m *PasswordMetrics) CompareAndSetPassword(ctx context.Context, userID influxdb.ID, old, new string) error { +func (m *PasswordMetrics) CompareAndSetPassword(ctx context.Context, userID platform.ID, old, new string) error { rec := m.rec.Record("compare_and_set_password") err := m.pwdService.CompareAndSetPassword(ctx, userID, old, new) return rec(err) diff --git a/tenant/service_bucket.go b/tenant/service_bucket.go index df818e7c8ab..6d1a49dfb62 100644 --- a/tenant/service_bucket.go +++ b/tenant/service_bucket.go @@ -5,6 +5,9 @@ import ( "fmt" "strings" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" ) @@ -22,7 +25,7 @@ func NewBucketSvc(st *Store, svc *Service) *BucketSvc { } // FindBucketByID returns a single bucket by ID. -func (s *BucketSvc) FindBucketByID(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { +func (s *BucketSvc) FindBucketByID(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { var bucket *influxdb.Bucket err := s.store.View(ctx, func(tx kv.Tx) error { b, err := s.store.GetBucket(ctx, tx, id) @@ -40,7 +43,7 @@ func (s *BucketSvc) FindBucketByID(ctx context.Context, id influxdb.ID) (*influx return bucket, nil } -func (s *BucketSvc) FindBucketByName(ctx context.Context, orgID influxdb.ID, name string) (*influxdb.Bucket, error) { +func (s *BucketSvc) FindBucketByName(ctx context.Context, orgID platform.ID, name string) (*influxdb.Bucket, error) { var bucket *influxdb.Bucket err := s.store.View(ctx, func(tx kv.Tx) error { b, err := s.store.GetBucketByName(ctx, tx, orgID, name) @@ -154,7 +157,7 @@ func (s *BucketSvc) CreateBucket(ctx context.Context, b *influxdb.Bucket) error // UpdateBucket updates a single bucket with changeset. // Returns the new bucket state after update. -func (s *BucketSvc) UpdateBucket(ctx context.Context, id influxdb.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { +func (s *BucketSvc) UpdateBucket(ctx context.Context, id platform.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { var bucket *influxdb.Bucket err := s.store.Update(ctx, func(tx kv.Tx) error { b, err := s.store.UpdateBucket(ctx, tx, id, upd) @@ -173,7 +176,7 @@ func (s *BucketSvc) UpdateBucket(ctx context.Context, id influxdb.ID, upd influx } // DeleteBucket removes a bucket by ID. -func (s *BucketSvc) DeleteBucket(ctx context.Context, id influxdb.ID) error { +func (s *BucketSvc) DeleteBucket(ctx context.Context, id platform.ID) error { err := s.store.Update(ctx, func(tx kv.Tx) error { bucket, err := s.store.GetBucket(ctx, tx, id) if err != nil { @@ -196,7 +199,7 @@ func (s *BucketSvc) DeleteBucket(ctx context.Context, id influxdb.ID) error { } // removeResourceRelations allows us to clean up any resource relationship that would have normally been left over after a delete action of a resource. -func (s *BucketSvc) removeResourceRelations(ctx context.Context, resourceID influxdb.ID) error { +func (s *BucketSvc) removeResourceRelations(ctx context.Context, resourceID platform.ID) error { urms, _, err := s.svc.FindUserResourceMappings(ctx, influxdb.UserResourceMappingFilter{ ResourceID: resourceID, }) @@ -216,16 +219,16 @@ func (s *BucketSvc) removeResourceRelations(ctx context.Context, resourceID infl func validBucketName(name string, typ influxdb.BucketType) error { // names starting with an underscore are reserved for system buckets if strings.HasPrefix(name, "_") && typ != influxdb.BucketTypeSystem { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("bucket name %s is invalid. Buckets may not start with underscore", name), Op: influxdb.OpCreateBucket, } } // quotation marks will cause queries to fail if strings.Contains(name, "\"") { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: fmt.Sprintf("bucket name %s is invalid. Bucket names may not include quotation marks", name), Op: influxdb.OpCreateBucket, } diff --git a/tenant/service_onboarding.go b/tenant/service_onboarding.go index 8f774e9fbcd..139ba71a7de 100644 --- a/tenant/service_onboarding.go +++ b/tenant/service_onboarding.go @@ -4,6 +4,8 @@ import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" icontext "github.com/influxdata/influxdb/v2/context" "github.com/influxdata/influxdb/v2/kv" @@ -78,18 +80,18 @@ func (s *OnboardService) OnboardInitialUser(ctx context.Context, req *influxdb.O return nil, ErrOnboardingNotAllowed } - return s.onboardUser(ctx, req, func(influxdb.ID, influxdb.ID) []influxdb.Permission { return influxdb.OperPermissions() }) + return s.onboardUser(ctx, req, func(platform.ID, platform.ID) []influxdb.Permission { return influxdb.OperPermissions() }) } // OnboardUser allows us to onboard a new user if is onboarding is allowed func (s *OnboardService) OnboardUser(ctx context.Context, req *influxdb.OnboardingRequest) (*influxdb.OnboardingResults, error) { - return s.onboardUser(ctx, req, func(orgID, userID influxdb.ID) []influxdb.Permission { + return s.onboardUser(ctx, req, func(orgID, userID platform.ID) []influxdb.Permission { return append(influxdb.OwnerPermissions(orgID), influxdb.MePermissions(userID)...) }) } // onboardUser allows us to onboard new users. -func (s *OnboardService) onboardUser(ctx context.Context, req *influxdb.OnboardingRequest, permFn func(orgID, userID influxdb.ID) []influxdb.Permission) (*influxdb.OnboardingResults, error) { +func (s *OnboardService) onboardUser(ctx context.Context, req *influxdb.OnboardingRequest, permFn func(orgID, userID platform.ID) []influxdb.Permission) (*influxdb.OnboardingResults, error) { if req == nil || req.User == "" || req.Org == "" || req.Bucket == "" { return nil, ErrOnboardInvalid } diff --git a/tenant/service_op_log.go b/tenant/service_op_log.go index 8272b76d9da..41369f574d0 100644 --- a/tenant/service_op_log.go +++ b/tenant/service_op_log.go @@ -5,6 +5,8 @@ import ( "encoding/json" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" ) @@ -41,7 +43,7 @@ func NewOpLogService(store kv.Store, opLogStore OpLogStore) *OpLogService { } // GetOrganizationOperationLog retrieves a organization operation log. -func (s *OpLogService) GetOrganizationOperationLog(ctx context.Context, id influxdb.ID, opts influxdb.FindOptions) ([]*influxdb.OperationLogEntry, int, error) { +func (s *OpLogService) GetOrganizationOperationLog(ctx context.Context, id platform.ID, opts influxdb.FindOptions) ([]*influxdb.OperationLogEntry, int, error) { // TODO(desa): might be worthwhile to allocate a slice of size opts.Limit log := []*influxdb.OperationLogEntry{} @@ -72,7 +74,7 @@ func (s *OpLogService) GetOrganizationOperationLog(ctx context.Context, id influ } // GetBucketOperationLog retrieves a buckets operation log. -func (s *OpLogService) GetBucketOperationLog(ctx context.Context, id influxdb.ID, opts influxdb.FindOptions) ([]*influxdb.OperationLogEntry, int, error) { +func (s *OpLogService) GetBucketOperationLog(ctx context.Context, id platform.ID, opts influxdb.FindOptions) ([]*influxdb.OperationLogEntry, int, error) { // TODO(desa): might be worthwhile to allocate a slice of size opts.Limit log := []*influxdb.OperationLogEntry{} @@ -103,7 +105,7 @@ func (s *OpLogService) GetBucketOperationLog(ctx context.Context, id influxdb.ID } // GetUserOperationLog retrieves a user operation log. -func (s *OpLogService) GetUserOperationLog(ctx context.Context, id influxdb.ID, opts influxdb.FindOptions) ([]*influxdb.OperationLogEntry, int, error) { +func (s *OpLogService) GetUserOperationLog(ctx context.Context, id platform.ID, opts influxdb.FindOptions) ([]*influxdb.OperationLogEntry, int, error) { // TODO(desa): might be worthwhile to allocate a slice of size opts.Limit log := []*influxdb.OperationLogEntry{} @@ -133,7 +135,7 @@ func (s *OpLogService) GetUserOperationLog(ctx context.Context, id influxdb.ID, return log, len(log), nil } -func encodeOrganizationOperationLogKey(id influxdb.ID) ([]byte, error) { +func encodeOrganizationOperationLogKey(id platform.ID) ([]byte, error) { buf, err := id.Encode() if err != nil { return nil, err @@ -141,7 +143,7 @@ func encodeOrganizationOperationLogKey(id influxdb.ID) ([]byte, error) { return append([]byte(orgOperationLogKeyPrefix), buf...), nil } -func encodeBucketOperationLogKey(id influxdb.ID) ([]byte, error) { +func encodeBucketOperationLogKey(id platform.ID) ([]byte, error) { buf, err := id.Encode() if err != nil { return nil, err @@ -149,7 +151,7 @@ func encodeBucketOperationLogKey(id influxdb.ID) ([]byte, error) { return append([]byte(bucketOperationLogKeyPrefix), buf...), nil } -func encodeUserOperationLogKey(id influxdb.ID) ([]byte, error) { +func encodeUserOperationLogKey(id platform.ID) ([]byte, error) { buf, err := id.Encode() if err != nil { return nil, err diff --git a/tenant/service_org.go b/tenant/service_org.go index 9fc2c340604..e45f94abf5a 100644 --- a/tenant/service_org.go +++ b/tenant/service_org.go @@ -3,6 +3,8 @@ package tenant import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" icontext "github.com/influxdata/influxdb/v2/context" "github.com/influxdata/influxdb/v2/kv" @@ -21,7 +23,7 @@ func NewOrganizationSvc(st *Store, svc *Service) *OrgSvc { } // Returns a single organization by ID. -func (s *OrgSvc) FindOrganizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { +func (s *OrgSvc) FindOrganizationByID(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { var org *influxdb.Organization err := s.store.View(ctx, func(tx kv.Tx) error { o, err := s.store.GetOrg(ctx, tx, id) @@ -170,7 +172,7 @@ func (s *OrgSvc) CreateOrganization(ctx context.Context, o *influxdb.Organizatio // Updates a single organization with changeset. // Returns the new organization state after update. -func (s *OrgSvc) UpdateOrganization(ctx context.Context, id influxdb.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { +func (s *OrgSvc) UpdateOrganization(ctx context.Context, id platform.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { var org *influxdb.Organization err := s.store.Update(ctx, func(tx kv.Tx) error { o, err := s.store.UpdateOrg(ctx, tx, id, upd) @@ -187,7 +189,7 @@ func (s *OrgSvc) UpdateOrganization(ctx context.Context, id influxdb.ID, upd inf } // DeleteOrganization removes a organization by ID and its dependent resources. -func (s *OrgSvc) DeleteOrganization(ctx context.Context, id influxdb.ID) error { +func (s *OrgSvc) DeleteOrganization(ctx context.Context, id platform.ID) error { // clean up the buckets for this organization filter := influxdb.BucketFilter{ OrganizationID: &id, @@ -215,7 +217,7 @@ func (s *OrgSvc) DeleteOrganization(ctx context.Context, id influxdb.ID) error { } // removeResourceRelations allows us to clean up any resource relationship that would have normally been left over after a delete action of a resource. -func (s *OrgSvc) removeResourceRelations(ctx context.Context, resourceID influxdb.ID) error { +func (s *OrgSvc) removeResourceRelations(ctx context.Context, resourceID platform.ID) error { urms, _, err := s.svc.FindUserResourceMappings(ctx, influxdb.UserResourceMappingFilter{ ResourceID: resourceID, }) diff --git a/tenant/service_urm.go b/tenant/service_urm.go index d7cb68a8d35..70683fcf6cf 100644 --- a/tenant/service_urm.go +++ b/tenant/service_urm.go @@ -3,6 +3,8 @@ package tenant import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" ) @@ -45,7 +47,7 @@ func (s *URMSvc) CreateUserResourceMapping(ctx context.Context, m *influxdb.User } // DeleteUserResourceMapping deletes a user resource mapping. -func (s *URMSvc) DeleteUserResourceMapping(ctx context.Context, resourceID, userID influxdb.ID) error { +func (s *URMSvc) DeleteUserResourceMapping(ctx context.Context, resourceID, userID platform.ID) error { err := s.store.Update(ctx, func(tx kv.Tx) error { _, err := s.store.GetURM(ctx, tx, resourceID, userID) if err != nil { diff --git a/tenant/service_urm_test.go b/tenant/service_urm_test.go index e8a0beb9b38..97312b5f080 100644 --- a/tenant/service_urm_test.go +++ b/tenant/service_urm_test.go @@ -2,6 +2,7 @@ package tenant_test import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" "testing" "github.com/influxdata/influxdb/v2" @@ -42,7 +43,7 @@ func initUserResourceMappingService(s kv.Store, f influxdbtesting.UserResourceFi } } - withID := func(gen *influxdb.IDGenerator, id influxdb.ID, fn func()) { + withID := func(gen *platform.IDGenerator, id platform.ID, fn func()) { idGen := *gen defer func() { *gen = idGen }() diff --git a/tenant/service_user.go b/tenant/service_user.go index 1814dfe2167..4728c73ac64 100644 --- a/tenant/service_user.go +++ b/tenant/service_user.go @@ -3,6 +3,9 @@ package tenant import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" "golang.org/x/crypto/bcrypt" @@ -21,7 +24,7 @@ func NewUserSvc(st *Store, svc *Service) *UserSvc { } // Returns a single user by ID. -func (s *UserSvc) FindUserByID(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { +func (s *UserSvc) FindUserByID(ctx context.Context, id platform.ID) (*influxdb.User, error) { var user *influxdb.User err := s.store.View(ctx, func(tx kv.Tx) error { u, err := s.store.GetUser(ctx, tx, id) @@ -114,7 +117,7 @@ func (s *UserSvc) CreateUser(ctx context.Context, u *influxdb.User) error { // Updates a single user with changeset. // Returns the new user state after update. { -func (s *UserSvc) UpdateUser(ctx context.Context, id influxdb.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { +func (s *UserSvc) UpdateUser(ctx context.Context, id platform.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { var user *influxdb.User err := s.store.Update(ctx, func(tx kv.Tx) error { u, err := s.store.UpdateUser(ctx, tx, id, upd) @@ -132,7 +135,7 @@ func (s *UserSvc) UpdateUser(ctx context.Context, id influxdb.ID, upd influxdb.U } // Removes a user by ID. -func (s *UserSvc) DeleteUser(ctx context.Context, id influxdb.ID) error { +func (s *UserSvc) DeleteUser(ctx context.Context, id platform.ID) error { err := s.store.Update(ctx, func(tx kv.Tx) error { err := s.store.DeletePassword(ctx, tx, id) if err != nil { @@ -144,7 +147,7 @@ func (s *UserSvc) DeleteUser(ctx context.Context, id influxdb.ID) error { } // FindPermissionForUser gets the full set of permission for a specified user id -func (s *UserSvc) FindPermissionForUser(ctx context.Context, uid influxdb.ID) (influxdb.PermissionSet, error) { +func (s *UserSvc) FindPermissionForUser(ctx context.Context, uid platform.ID) (influxdb.PermissionSet, error) { mappings, _, err := s.svc.FindUserResourceMappings(ctx, influxdb.UserResourceMappingFilter{UserID: uid}, influxdb.FindOptions{Limit: 100}) if err != nil { return nil, err @@ -176,7 +179,7 @@ func (s *UserSvc) FindPermissionForUser(ctx context.Context, uid influxdb.ID) (i } // SetPassword overrides the password of a known user. -func (s *UserSvc) SetPassword(ctx context.Context, userID influxdb.ID, password string) error { +func (s *UserSvc) SetPassword(ctx context.Context, userID platform.ID, password string) error { if len(password) < MinPasswordLen { return EShortPassword } @@ -196,7 +199,7 @@ func (s *UserSvc) SetPassword(ctx context.Context, userID influxdb.ID, password // ComparePassword checks if the password matches the password recorded. // Passwords that do not match return errors. -func (s *UserSvc) ComparePassword(ctx context.Context, userID influxdb.ID, password string) error { +func (s *UserSvc) ComparePassword(ctx context.Context, userID platform.ID, password string) error { // get password var hash []byte err := s.store.View(ctx, func(tx kv.Tx) error { @@ -228,7 +231,7 @@ func (s *UserSvc) ComparePassword(ctx context.Context, userID influxdb.ID, passw // CompareAndSetPassword checks the password and if they match // updates to the new password. -func (s *UserSvc) CompareAndSetPassword(ctx context.Context, userID influxdb.ID, old, new string) error { +func (s *UserSvc) CompareAndSetPassword(ctx context.Context, userID platform.ID, old, new string) error { err := s.ComparePassword(ctx, userID, old) if err != nil { return err @@ -250,7 +253,7 @@ func permissionFromMapping(mappings []*influxdb.UserResourceMapping) ([]influxdb for _, m := range mappings { p, err := m.ToPermissions() if err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } diff --git a/tenant/service_user_test.go b/tenant/service_user_test.go index 372a1883c66..5f082242bd2 100644 --- a/tenant/service_user_test.go +++ b/tenant/service_user_test.go @@ -2,6 +2,7 @@ package tenant_test import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" "testing" "github.com/google/go-cmp/cmp" @@ -135,7 +136,7 @@ func TestFindPermissionsFromUser(t *testing.T) { t.Fatal(err) } - orgID := influxdb.ID(1) + orgID := platform.ID(1) expected := influxdb.PermissionSet{ influxdb.Permission{Action: influxdb.ReadAction, Resource: influxdb.Resource{OrgID: &orgID, Type: influxdb.AuthorizationsResourceType}}, influxdb.Permission{Action: influxdb.ReadAction, Resource: influxdb.Resource{OrgID: &orgID, Type: influxdb.BucketsResourceType}}, diff --git a/tenant/storage.go b/tenant/storage.go index 841786e351b..c7895ffdac0 100644 --- a/tenant/storage.go +++ b/tenant/storage.go @@ -4,7 +4,9 @@ import ( "context" "time" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2/kit/tracing" "github.com/influxdata/influxdb/v2/kv" "github.com/influxdata/influxdb/v2/rand" @@ -16,9 +18,9 @@ const MaxIDGenerationN = 100 type Store struct { kvStore kv.Store - IDGen influxdb.IDGenerator - OrgIDGen influxdb.IDGenerator - BucketIDGen influxdb.IDGenerator + IDGen platform.IDGenerator + OrgIDGen platform.IDGenerator + BucketIDGen platform.IDGenerator now func() time.Time @@ -59,7 +61,7 @@ func (s *Store) Update(ctx context.Context, fn func(kv.Tx) error) error { // generateSafeID attempts to create ids for buckets // and orgs that are without backslash, commas, and spaces, BUT ALSO do not already exist. -func (s *Store) generateSafeID(ctx context.Context, tx kv.Tx, bucket []byte, gen influxdb.IDGenerator) (influxdb.ID, error) { +func (s *Store) generateSafeID(ctx context.Context, tx kv.Tx, bucket []byte, gen platform.IDGenerator) (platform.ID, error) { for i := 0; i < MaxIDGenerationN; i++ { id := gen.ID() @@ -72,20 +74,20 @@ func (s *Store) generateSafeID(ctx context.Context, tx kv.Tx, bucket []byte, gen continue } - return influxdb.InvalidID(), err + return platform.InvalidID(), err } - return influxdb.InvalidID(), ErrFailureGeneratingID + return platform.InvalidID(), ErrFailureGeneratingID } -func (s *Store) uniqueID(ctx context.Context, tx kv.Tx, bucket []byte, id influxdb.ID) error { +func (s *Store) uniqueID(ctx context.Context, tx kv.Tx, bucket []byte, id platform.ID) error { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() encodedID, err := id.Encode() if err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Err: err, } } diff --git a/tenant/storage_bucket.go b/tenant/storage_bucket.go index 7318e58dbe3..1502e3b7cf8 100644 --- a/tenant/storage_bucket.go +++ b/tenant/storage_bucket.go @@ -4,6 +4,9 @@ import ( "context" "encoding/json" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" ) @@ -13,23 +16,23 @@ var ( bucketIndex = []byte("bucketindexv1") ) -func bucketIndexKey(o influxdb.ID, name string) ([]byte, error) { +func bucketIndexKey(o platform.ID, name string) ([]byte, error) { orgID, err := o.Encode() if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } - k := make([]byte, influxdb.IDLength+len(name)) + k := make([]byte, platform.IDLength+len(name)) copy(k, orgID) - copy(k[influxdb.IDLength:], name) + copy(k[platform.IDLength:], name) return k, nil } // uniqueBucketName ensures this bucket is unique for this organization -func (s *Store) uniqueBucketName(ctx context.Context, tx kv.Tx, oid influxdb.ID, uname string) error { +func (s *Store) uniqueBucketName(ctx context.Context, tx kv.Tx, oid platform.ID, uname string) error { key, err := bucketIndexKey(oid, uname) if err != nil { return err @@ -76,7 +79,7 @@ func marshalBucket(u *influxdb.Bucket) ([]byte, error) { return v, nil } -func (s *Store) GetBucket(ctx context.Context, tx kv.Tx, id influxdb.ID) (*influxdb.Bucket, error) { +func (s *Store) GetBucket(ctx context.Context, tx kv.Tx, id platform.ID) (*influxdb.Bucket, error) { encodedID, err := id.Encode() if err != nil { return nil, InvalidOrgIDError(err) @@ -99,11 +102,11 @@ func (s *Store) GetBucket(ctx context.Context, tx kv.Tx, id influxdb.ID) (*influ return unmarshalBucket(v) } -func (s *Store) GetBucketByName(ctx context.Context, tx kv.Tx, orgID influxdb.ID, n string) (*influxdb.Bucket, error) { +func (s *Store) GetBucketByName(ctx context.Context, tx kv.Tx, orgID platform.ID, n string) (*influxdb.Bucket, error) { key, err := bucketIndexKey(orgID, n) if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -124,9 +127,9 @@ func (s *Store) GetBucketByName(ctx context.Context, tx kv.Tx, orgID influxdb.ID return nil, err } - var id influxdb.ID + var id platform.ID if err := id.Decode(buf); err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -135,7 +138,7 @@ func (s *Store) GetBucketByName(ctx context.Context, tx kv.Tx, orgID influxdb.ID type BucketFilter struct { Name *string - OrganizationID *influxdb.ID + OrganizationID *platform.ID } func (s *Store) ListBuckets(ctx context.Context, tx kv.Tx, filter BucketFilter, opt ...influxdb.FindOptions) ([]*influxdb.Bucket, error) { @@ -210,12 +213,12 @@ func (s *Store) ListBuckets(ctx context.Context, tx kv.Tx, filter BucketFilter, return bs, cursor.Err() } -func (s *Store) listBucketsByOrg(ctx context.Context, tx kv.Tx, orgID influxdb.ID, o influxdb.FindOptions) ([]*influxdb.Bucket, error) { +func (s *Store) listBucketsByOrg(ctx context.Context, tx kv.Tx, orgID platform.ID, o influxdb.FindOptions) ([]*influxdb.Bucket, error) { // get the prefix key (org id with an empty name) key, err := bucketIndexKey(orgID, "") if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -243,9 +246,9 @@ func (s *Store) listBucketsByOrg(ctx context.Context, tx kv.Tx, orgID influxdb.I return nil, err } - var id influxdb.ID + var id platform.ID if err := id.Decode(v); err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -313,7 +316,7 @@ func (s *Store) CreateBucket(ctx context.Context, tx kv.Tx, bucket *influxdb.Buc return nil } -func (s *Store) UpdateBucket(ctx context.Context, tx kv.Tx, id influxdb.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { +func (s *Store) UpdateBucket(ctx context.Context, tx kv.Tx, id platform.ID, upd influxdb.BucketUpdate) (*influxdb.Bucket, error) { encodedID, err := id.Encode() if err != nil { return nil, err @@ -391,7 +394,7 @@ func (s *Store) UpdateBucket(ctx context.Context, tx kv.Tx, id influxdb.ID, upd return bucket, nil } -func (s *Store) DeleteBucket(ctx context.Context, tx kv.Tx, id influxdb.ID) error { +func (s *Store) DeleteBucket(ctx context.Context, tx kv.Tx, id platform.ID) error { bucket, err := s.GetBucket(ctx, tx, id) if err != nil { return err diff --git a/tenant/storage_bucket_test.go b/tenant/storage_bucket_test.go index 9cd1aea1ca9..7e456e6660c 100644 --- a/tenant/storage_bucket_test.go +++ b/tenant/storage_bucket_test.go @@ -3,6 +3,7 @@ package tenant_test import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" "reflect" "testing" "time" @@ -27,14 +28,14 @@ import ( // } const ( - firstBucketID influxdb.ID = (iota + 1) + firstBucketID platform.ID = (iota + 1) secondBucketID thirdBucketID fourthBucketID fifthBucketID ) -var orgIDs = []influxdb.ID{firstOrgID, secondOrgID} +var orgIDs = []platform.ID{firstOrgID, secondOrgID} func TestBucket(t *testing.T) { var ( @@ -45,7 +46,7 @@ func TestBucket(t *testing.T) { testBuckets = func(count int, visit ...func(*influxdb.Bucket)) (buckets []*influxdb.Bucket) { buckets = make([]*influxdb.Bucket, count) for i := range buckets { - id := firstBucketID + influxdb.ID(i) + id := firstBucketID + platform.ID(i) // flip-flop between (reserved_id + reserved_id+1) orgID := orgIDs[i%2] buckets[i] = &influxdb.Bucket{ @@ -188,9 +189,9 @@ func TestBucket(t *testing.T) { var ( expected = testBuckets(10, withCrudLog) found []*influxdb.Bucket - lastID *influxdb.ID + lastID *platform.ID limit = 3 - listAfter = func(after *influxdb.ID) ([]*influxdb.Bucket, error) { + listAfter = func(after *platform.ID) ([]*influxdb.Bucket, error) { return store.ListBuckets(context.Background(), tx, tenant.BucketFilter{}, influxdb.FindOptions{ After: after, Limit: limit, diff --git a/tenant/storage_org.go b/tenant/storage_org.go index 9d2fcfe85e4..391d0e99312 100644 --- a/tenant/storage_org.go +++ b/tenant/storage_org.go @@ -5,6 +5,8 @@ import ( "encoding/json" "strings" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" ) @@ -63,7 +65,7 @@ func marshalOrg(u *influxdb.Organization) ([]byte, error) { return v, nil } -func (s *Store) GetOrg(ctx context.Context, tx kv.Tx, id influxdb.ID) (*influxdb.Organization, error) { +func (s *Store) GetOrg(ctx context.Context, tx kv.Tx, id platform.ID) (*influxdb.Organization, error) { encodedID, err := id.Encode() if err != nil { return nil, InvalidOrgIDError(err) @@ -101,9 +103,9 @@ func (s *Store) GetOrgByName(ctx context.Context, tx kv.Tx, n string) (*influxdb return nil, ErrInternalServiceError(err) } - var id influxdb.ID + var id platform.ID if err := id.Decode(uid); err != nil { - return nil, influxdb.ErrCorruptID(err) + return nil, platform.ErrCorruptID(err) } return s.GetOrg(ctx, tx, id) } @@ -198,7 +200,7 @@ func (s *Store) CreateOrg(ctx context.Context, tx kv.Tx, o *influxdb.Organizatio return nil } -func (s *Store) UpdateOrg(ctx context.Context, tx kv.Tx, id influxdb.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { +func (s *Store) UpdateOrg(ctx context.Context, tx kv.Tx, id platform.ID, upd influxdb.OrganizationUpdate) (*influxdb.Organization, error) { encodedID, err := id.Encode() if err != nil { return nil, err @@ -251,7 +253,7 @@ func (s *Store) UpdateOrg(ctx context.Context, tx kv.Tx, id influxdb.ID, upd inf return u, nil } -func (s *Store) DeleteOrg(ctx context.Context, tx kv.Tx, id influxdb.ID) error { +func (s *Store) DeleteOrg(ctx context.Context, tx kv.Tx, id platform.ID) error { u, err := s.GetOrg(ctx, tx, id) if err != nil { return err diff --git a/tenant/storage_org_test.go b/tenant/storage_org_test.go index 96b2ef1d201..d803e1ab6e1 100644 --- a/tenant/storage_org_test.go +++ b/tenant/storage_org_test.go @@ -3,6 +3,7 @@ package tenant_test import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" "testing" "time" @@ -22,7 +23,7 @@ import ( // } const ( - firstOrgID influxdb.ID = (iota + 1) + firstOrgID platform.ID = (iota + 1) secondOrgID thirdOrgID fourthOrgID @@ -35,7 +36,7 @@ func TestOrg(t *testing.T) { testOrgs = func(count int, visit ...func(*influxdb.Organization)) (orgs []*influxdb.Organization) { for i := 1; i <= count; i++ { org := &influxdb.Organization{ - ID: influxdb.ID(i), + ID: platform.ID(i), Name: fmt.Sprintf("org%d", i), Description: "words", } diff --git a/tenant/storage_urm.go b/tenant/storage_urm.go index 2e896e863a8..79e4b0cb31e 100644 --- a/tenant/storage_urm.go +++ b/tenant/storage_urm.go @@ -4,6 +4,8 @@ import ( "context" "encoding/json" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" ) @@ -133,7 +135,7 @@ func (s *Store) ListURMs(ctx context.Context, tx kv.Tx, filter influxdb.UserReso return ms, cur.Err() } -func (s *Store) GetURM(ctx context.Context, tx kv.Tx, resourceID, userID influxdb.ID) (*influxdb.UserResourceMapping, error) { +func (s *Store) GetURM(ctx context.Context, tx kv.Tx, resourceID, userID platform.ID) (*influxdb.UserResourceMapping, error) { key, err := userResourceKey(resourceID, userID) if err != nil { return nil, err @@ -156,7 +158,7 @@ func (s *Store) GetURM(ctx context.Context, tx kv.Tx, resourceID, userID influxd return m, nil } -func (s *Store) DeleteURM(ctx context.Context, tx kv.Tx, resourceID, userID influxdb.ID) error { +func (s *Store) DeleteURM(ctx context.Context, tx kv.Tx, resourceID, userID platform.ID) error { key, err := userResourceKey(resourceID, userID) if err != nil { return err @@ -180,7 +182,7 @@ func (s *Store) DeleteURM(ctx context.Context, tx kv.Tx, resourceID, userID infl return b.Delete(key) } -func userResourcePrefixKey(resourceID influxdb.ID) ([]byte, error) { +func userResourcePrefixKey(resourceID platform.ID) ([]byte, error) { encodedResourceID, err := resourceID.Encode() if err != nil { return nil, ErrInvalidURMID @@ -188,7 +190,7 @@ func userResourcePrefixKey(resourceID influxdb.ID) ([]byte, error) { return encodedResourceID, nil } -func userResourceKey(resourceID, userID influxdb.ID) ([]byte, error) { +func userResourceKey(resourceID, userID platform.ID) ([]byte, error) { encodedResourceID, err := resourceID.Encode() if err != nil { return nil, ErrInvalidURMID diff --git a/tenant/storage_urm_test.go b/tenant/storage_urm_test.go index 3aa33a8bc01..a77e6f0e338 100644 --- a/tenant/storage_urm_test.go +++ b/tenant/storage_urm_test.go @@ -3,6 +3,8 @@ package tenant_test import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "reflect" "sort" "testing" @@ -17,7 +19,7 @@ func TestURM(t *testing.T) { simpleSetup := func(t *testing.T, store *tenant.Store, tx kv.Tx) { for i := 1; i <= 10; i++ { // User must exist to create urm. - uid := influxdb.ID(i + 1) + uid := platform.ID(i + 1) err := store.CreateUser(context.Background(), tx, &influxdb.User{ ID: uid, Name: fmt.Sprintf("user%d", i), @@ -30,7 +32,7 @@ func TestURM(t *testing.T) { UserType: influxdb.Owner, MappingType: influxdb.UserMappingType, ResourceType: influxdb.OrgsResourceType, - ResourceID: influxdb.ID(i%2 + 1), + ResourceID: platform.ID(i%2 + 1), }) if err != nil { t.Fatal(err) @@ -59,11 +61,11 @@ func TestURM(t *testing.T) { var expected []*influxdb.UserResourceMapping for i := 1; i <= 10; i++ { expected = append(expected, &influxdb.UserResourceMapping{ - UserID: influxdb.ID(i + 1), + UserID: platform.ID(i + 1), UserType: influxdb.Owner, MappingType: influxdb.UserMappingType, ResourceType: influxdb.OrgsResourceType, - ResourceID: influxdb.ID(i%2 + 1), + ResourceID: platform.ID(i%2 + 1), }) } sort.Slice(expected, func(i, j int) bool { @@ -88,7 +90,7 @@ func TestURM(t *testing.T) { t.Fatal(err) } - maxID := influxdb.ID(0) + maxID := platform.ID(0) for _, u := range users { if u.ID > maxID { maxID = u.ID @@ -100,11 +102,11 @@ func TestURM(t *testing.T) { UserType: influxdb.Owner, MappingType: influxdb.UserMappingType, ResourceType: influxdb.OrgsResourceType, - ResourceID: influxdb.ID(1), + ResourceID: platform.ID(1), }) if err == nil { t.Fatal("expected error got none") - } else if influxdb.ErrorCode(err) != influxdb.ENotFound { + } else if errors.ErrorCode(err) != errors.ENotFound { t.Fatalf("expected not found error got: %v", err) } }, @@ -150,11 +152,11 @@ func TestURM(t *testing.T) { var expected []*influxdb.UserResourceMapping for i := 1; i <= 10; i++ { expected = append(expected, &influxdb.UserResourceMapping{ - UserID: influxdb.ID(i + 1), + UserID: platform.ID(i + 1), UserType: influxdb.Owner, MappingType: influxdb.UserMappingType, ResourceType: influxdb.OrgsResourceType, - ResourceID: influxdb.ID(i%2 + 1), + ResourceID: platform.ID(i%2 + 1), }) } sort.Slice(expected, func(i, j int) bool { @@ -169,7 +171,7 @@ func TestURM(t *testing.T) { t.Fatalf("expected identical urms: \n%s", cmp.Diff(urms, expected)) } - urms, err = store.ListURMs(context.Background(), tx, influxdb.UserResourceMappingFilter{ResourceID: influxdb.ID(1)}) + urms, err = store.ListURMs(context.Background(), tx, influxdb.UserResourceMappingFilter{ResourceID: platform.ID(1)}) if err != nil { t.Fatal(err) } @@ -187,7 +189,7 @@ func TestURM(t *testing.T) { { name: "list by user with limit", setup: func(t *testing.T, store *tenant.Store, tx kv.Tx) { - uid := influxdb.ID(1) + uid := platform.ID(1) err := store.CreateUser(context.Background(), tx, &influxdb.User{ ID: uid, Name: "user", @@ -202,7 +204,7 @@ func TestURM(t *testing.T) { UserType: influxdb.Owner, MappingType: influxdb.UserMappingType, ResourceType: influxdb.OrgsResourceType, - ResourceID: influxdb.ID(i + 1), + ResourceID: platform.ID(i + 1), }) if err != nil { t.Fatal(err) @@ -210,7 +212,7 @@ func TestURM(t *testing.T) { } }, results: func(t *testing.T, store *tenant.Store, tx kv.Tx) { - urms, err := store.ListURMs(context.Background(), tx, influxdb.UserResourceMappingFilter{UserID: influxdb.ID(1)}, influxdb.FindOptions{Limit: 10}) + urms, err := store.ListURMs(context.Background(), tx, influxdb.UserResourceMappingFilter{UserID: platform.ID(1)}, influxdb.FindOptions{Limit: 10}) if err != nil { t.Fatal(err) } @@ -221,11 +223,11 @@ func TestURM(t *testing.T) { var expected []*influxdb.UserResourceMapping for i := 1; i <= 10; i++ { expected = append(expected, &influxdb.UserResourceMapping{ - UserID: influxdb.ID(1), + UserID: platform.ID(1), UserType: influxdb.Owner, MappingType: influxdb.UserMappingType, ResourceType: influxdb.OrgsResourceType, - ResourceID: influxdb.ID(i + 1), + ResourceID: platform.ID(i + 1), }) } sort.Slice(expected, func(i, j int) bool { @@ -244,7 +246,7 @@ func TestURM(t *testing.T) { { name: "list by user with limit and offset", setup: func(t *testing.T, store *tenant.Store, tx kv.Tx) { - uid := influxdb.ID(1) + uid := platform.ID(1) err := store.CreateUser(context.Background(), tx, &influxdb.User{ ID: uid, Name: "user", @@ -259,7 +261,7 @@ func TestURM(t *testing.T) { UserType: influxdb.Owner, MappingType: influxdb.UserMappingType, ResourceType: influxdb.OrgsResourceType, - ResourceID: influxdb.ID(i + 1), + ResourceID: platform.ID(i + 1), }) if err != nil { t.Fatal(err) @@ -271,7 +273,7 @@ func TestURM(t *testing.T) { context.Background(), tx, influxdb.UserResourceMappingFilter{ - UserID: influxdb.ID(1)}, + UserID: platform.ID(1)}, influxdb.FindOptions{ Offset: 10, Limit: 10, @@ -287,11 +289,11 @@ func TestURM(t *testing.T) { var expected []*influxdb.UserResourceMapping for i := 11; i <= 20; i++ { expected = append(expected, &influxdb.UserResourceMapping{ - UserID: influxdb.ID(1), + UserID: platform.ID(1), UserType: influxdb.Owner, MappingType: influxdb.UserMappingType, ResourceType: influxdb.OrgsResourceType, - ResourceID: influxdb.ID(i + 1), + ResourceID: platform.ID(i + 1), }) } sort.Slice(expected, func(i, j int) bool { diff --git a/tenant/storage_user.go b/tenant/storage_user.go index 68ef8623f1a..d54b8a7c54d 100644 --- a/tenant/storage_user.go +++ b/tenant/storage_user.go @@ -4,6 +4,8 @@ import ( "context" "encoding/json" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" ) @@ -55,7 +57,7 @@ func (s *Store) uniqueUserName(ctx context.Context, tx kv.Tx, uname string) erro return ErrUnprocessableUser(err) } -func (s *Store) GetUser(ctx context.Context, tx kv.Tx, id influxdb.ID) (*influxdb.User, error) { +func (s *Store) GetUser(ctx context.Context, tx kv.Tx, id platform.ID) (*influxdb.User, error) { encodedID, err := id.Encode() if err != nil { return nil, InvalidUserIDError(err) @@ -93,9 +95,9 @@ func (s *Store) GetUserByName(ctx context.Context, tx kv.Tx, n string) (*influxd return nil, ErrInternalServiceError(err) } - var id influxdb.ID + var id platform.ID if err := id.Decode(uid); err != nil { - return nil, influxdb.ErrCorruptID(err) + return nil, platform.ErrCorruptID(err) } return s.GetUser(ctx, tx, id) } @@ -185,7 +187,7 @@ func (s *Store) CreateUser(ctx context.Context, tx kv.Tx, u *influxdb.User) erro return nil } -func (s *Store) UpdateUser(ctx context.Context, tx kv.Tx, id influxdb.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { +func (s *Store) UpdateUser(ctx context.Context, tx kv.Tx, id platform.ID, upd influxdb.UserUpdate) (*influxdb.User, error) { encodedID, err := id.Encode() if err != nil { return nil, err @@ -237,7 +239,7 @@ func (s *Store) UpdateUser(ctx context.Context, tx kv.Tx, id influxdb.ID, upd in return u, nil } -func (s *Store) DeleteUser(ctx context.Context, tx kv.Tx, id influxdb.ID) error { +func (s *Store) DeleteUser(ctx context.Context, tx kv.Tx, id platform.ID) error { u, err := s.GetUser(ctx, tx, id) if err != nil { return err @@ -291,7 +293,7 @@ func (s *Store) DeleteUser(ctx context.Context, tx kv.Tx, id influxdb.ID) error return aggErr.Err() } -func (s *Store) GetPassword(ctx context.Context, tx kv.Tx, id influxdb.ID) (string, error) { +func (s *Store) GetPassword(ctx context.Context, tx kv.Tx, id platform.ID) (string, error) { encodedID, err := id.Encode() if err != nil { return "", InvalidUserIDError(err) @@ -307,7 +309,7 @@ func (s *Store) GetPassword(ctx context.Context, tx kv.Tx, id influxdb.ID) (stri return string(passwd), err } -func (s *Store) SetPassword(ctx context.Context, tx kv.Tx, id influxdb.ID, password string) error { +func (s *Store) SetPassword(ctx context.Context, tx kv.Tx, id platform.ID, password string) error { encodedID, err := id.Encode() if err != nil { return InvalidUserIDError(err) @@ -321,7 +323,7 @@ func (s *Store) SetPassword(ctx context.Context, tx kv.Tx, id influxdb.ID, passw return b.Put(encodedID, []byte(password)) } -func (s *Store) DeletePassword(ctx context.Context, tx kv.Tx, id influxdb.ID) error { +func (s *Store) DeletePassword(ctx context.Context, tx kv.Tx, id platform.ID) error { encodedID, err := id.Encode() if err != nil { return InvalidUserIDError(err) diff --git a/tenant/storage_user_test.go b/tenant/storage_user_test.go index afeedffe848..a5e9a014f12 100644 --- a/tenant/storage_user_test.go +++ b/tenant/storage_user_test.go @@ -3,6 +3,7 @@ package tenant_test import ( "context" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" "reflect" "testing" @@ -15,7 +16,7 @@ func TestUser(t *testing.T) { simpleSetup := func(t *testing.T, store *tenant.Store, tx kv.Tx) { for i := 1; i <= 10; i++ { err := store.CreateUser(context.Background(), tx, &influxdb.User{ - ID: influxdb.ID(i), + ID: platform.ID(i), Name: fmt.Sprintf("user%d", i), Status: "active", }) @@ -47,7 +48,7 @@ func TestUser(t *testing.T) { expected := []*influxdb.User{} for i := 1; i <= 10; i++ { expected = append(expected, &influxdb.User{ - ID: influxdb.ID(i), + ID: platform.ID(i), Name: fmt.Sprintf("user%d", i), Status: "active", }) @@ -111,7 +112,7 @@ func TestUser(t *testing.T) { expected := []*influxdb.User{} for i := 1; i <= 10; i++ { expected = append(expected, &influxdb.User{ - ID: influxdb.ID(i), + ID: platform.ID(i), Name: fmt.Sprintf("user%d", i), Status: "active", }) @@ -150,19 +151,19 @@ func TestUser(t *testing.T) { setup: simpleSetup, update: func(t *testing.T, store *tenant.Store, tx kv.Tx) { user5 := "user5" - _, err := store.UpdateUser(context.Background(), tx, influxdb.ID(3), influxdb.UserUpdate{Name: &user5}) + _, err := store.UpdateUser(context.Background(), tx, platform.ID(3), influxdb.UserUpdate{Name: &user5}) if err.Error() != tenant.UserAlreadyExistsError(user5).Error() { t.Fatal("failed to error on duplicate username") } user30 := "user30" - _, err = store.UpdateUser(context.Background(), tx, influxdb.ID(3), influxdb.UserUpdate{Name: &user30}) + _, err = store.UpdateUser(context.Background(), tx, platform.ID(3), influxdb.UserUpdate{Name: &user30}) if err != nil { t.Fatal(err) } inactive := influxdb.Status("inactive") - _, err = store.UpdateUser(context.Background(), tx, influxdb.ID(3), influxdb.UserUpdate{Status: &inactive}) + _, err = store.UpdateUser(context.Background(), tx, platform.ID(3), influxdb.UserUpdate{Status: &inactive}) if err != nil { t.Fatal(err) } @@ -180,7 +181,7 @@ func TestUser(t *testing.T) { expected := []*influxdb.User{} for i := 1; i <= 10; i++ { expected = append(expected, &influxdb.User{ - ID: influxdb.ID(i), + ID: platform.ID(i), Name: fmt.Sprintf("user%d", i), Status: "active", }) @@ -226,7 +227,7 @@ func TestUser(t *testing.T) { for i := 1; i <= 10; i++ { if i != 1 && i != 3 { expected = append(expected, &influxdb.User{ - ID: influxdb.ID(i), + ID: platform.ID(i), Name: fmt.Sprintf("user%d", i), Status: "active", }) diff --git a/testing/auth.go b/testing/auth.go index 1a9e8a5c2af..e96247bb0ed 100644 --- a/testing/auth.go +++ b/testing/auth.go @@ -7,6 +7,9 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/influxdata/influxdb/v2" @@ -49,8 +52,8 @@ func WithoutFindByToken() AuthTestOpts { // AuthorizationFields will include the IDGenerator, and authorizations type AuthorizationFields struct { - IDGenerator influxdb.IDGenerator - OrgIDGenerator influxdb.IDGenerator + IDGenerator platform.IDGenerator + OrgIDGenerator platform.IDGenerator TokenGenerator influxdb.TokenGenerator TimeGenerator influxdb.TimeGenerator Authorizations []*influxdb.Authorization @@ -441,7 +444,7 @@ func UpdateAuthorization( t *testing.T, ) { type args struct { - id influxdb.ID + id platform.ID upd *influxdb.AuthorizationUpdate } type wants struct { @@ -587,8 +590,8 @@ func UpdateAuthorization( }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpUpdateAuthorization, Msg: "authorization not found", }, @@ -658,8 +661,8 @@ func UpdateAuthorization( }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Op: influxdb.OpUpdateAuthorization, Msg: "unknown authorization status", }, @@ -866,9 +869,9 @@ func FindAuthorizations( t *testing.T, ) { type args struct { - ID influxdb.ID - UserID influxdb.ID - OrgID influxdb.ID + ID platform.ID + UserID platform.ID + OrgID platform.ID token string } @@ -1189,7 +1192,7 @@ func DeleteAuthorization( t *testing.T, ) { type args struct { - ID influxdb.ID + ID platform.ID } type wants struct { err error @@ -1294,8 +1297,8 @@ func DeleteAuthorization( ID: MustIDBase16(authThreeID), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "authorization not found", Op: influxdb.OpDeleteAuthorization, }, @@ -1341,20 +1344,20 @@ func DeleteAuthorization( } } -func allUsersPermission(orgID influxdb.ID) []influxdb.Permission { +func allUsersPermission(orgID platform.ID) []influxdb.Permission { return []influxdb.Permission{ {Action: influxdb.WriteAction, Resource: influxdb.Resource{Type: influxdb.UsersResourceType, OrgID: &orgID}}, {Action: influxdb.ReadAction, Resource: influxdb.Resource{Type: influxdb.UsersResourceType, OrgID: &orgID}}, } } -func createUsersPermission(orgID influxdb.ID) []influxdb.Permission { +func createUsersPermission(orgID platform.ID) []influxdb.Permission { return []influxdb.Permission{ {Action: influxdb.WriteAction, Resource: influxdb.Resource{Type: influxdb.UsersResourceType, OrgID: &orgID}}, } } -func deleteUsersPermission(orgID influxdb.ID) []influxdb.Permission { +func deleteUsersPermission(orgID platform.ID) []influxdb.Permission { return []influxdb.Permission{ {Action: influxdb.WriteAction, Resource: influxdb.Resource{Type: influxdb.UsersResourceType, OrgID: &orgID}}, } diff --git a/testing/bucket_service.go b/testing/bucket_service.go index 2ad64386d5f..02bf10865da 100644 --- a/testing/bucket_service.go +++ b/testing/bucket_service.go @@ -7,6 +7,9 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/dustin/go-humanize" "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" @@ -14,7 +17,7 @@ import ( ) const ( - idOne = influxdb.ID(iota + 1) + idOne = platform.ID(iota + 1) idTwo idThree idFour @@ -51,9 +54,9 @@ var bucketCmpOptions = cmp.Options{ // BucketFields will include the IDGenerator, and buckets type BucketFields struct { - IDGenerator influxdb.IDGenerator - OrgIDs influxdb.IDGenerator - BucketIDs influxdb.IDGenerator + IDGenerator platform.IDGenerator + OrgIDs platform.IDGenerator + BucketIDs platform.IDGenerator TimeGenerator influxdb.TimeGenerator Buckets []*influxdb.Bucket Organizations []*influxdb.Organization @@ -256,8 +259,8 @@ func CreateBucket( OrgID: idOne, }, }, - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Op: influxdb.OpCreateBucket, Msg: "bucket with name bucket1 already exists", }, @@ -333,8 +336,8 @@ func CreateBucket( }, wants: wants{ buckets: []*influxdb.Bucket{}, - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "organization not found", Op: influxdb.OpCreateBucket, }, @@ -362,8 +365,8 @@ func CreateBucket( }, wants: wants{ buckets: []*influxdb.Bucket{}, - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Op: influxdb.OpCreateBucket, Msg: "bucket name namewith\"quote is invalid. Bucket names may not include quotation marks", }, @@ -410,7 +413,7 @@ func FindBucketByID( t *testing.T, ) { type args struct { - id influxdb.ID + id platform.ID } type wants struct { err error @@ -487,8 +490,8 @@ func FindBucketByID( id: idThree, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindBucketByID, Msg: "bucket not found", }, @@ -518,10 +521,10 @@ func FindBuckets( t *testing.T, ) { type args struct { - ID influxdb.ID + ID platform.ID name string organization string - organizationID influxdb.ID + organizationID platform.ID findOptions influxdb.FindOptions } @@ -928,7 +931,7 @@ func DeleteBucket( t *testing.T, ) { type args struct { - ID influxdb.ID + ID platform.ID } type wants struct { err error @@ -1006,10 +1009,10 @@ func DeleteBucket( ID: MustIDBase16("1234567890654321"), }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Op: influxdb.OpDeleteBucket, Msg: "bucket not found", - Code: influxdb.ENotFound, + Code: errors.ENotFound, }, buckets: []*influxdb.Bucket{ { @@ -1049,10 +1052,10 @@ func DeleteBucket( ID: idOne, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Op: influxdb.OpDeleteBucket, Msg: "system buckets cannot be deleted", - Code: influxdb.EInvalid, + Code: errors.EInvalid, }, buckets: []*influxdb.Bucket{ { @@ -1102,8 +1105,8 @@ func FindBucket( ) { type args struct { name string - organizationID influxdb.ID - id influxdb.ID + organizationID platform.ID + id platform.ID } type wants struct { @@ -1215,8 +1218,8 @@ func FindBucket( organizationID: idOne, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindBucket, Msg: "bucket \"xyz\" not found", }, @@ -1257,7 +1260,7 @@ func UpdateBucket( ) { type args struct { name string - id influxdb.ID + id platform.ID retention int shardDuration int description *string @@ -1343,8 +1346,8 @@ func UpdateBucket( name: "bucket2", }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Msg: "bucket name is not unique", }, }, @@ -1375,8 +1378,8 @@ func UpdateBucket( name: "bucket2", }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "system buckets cannot be renamed", }, }, @@ -1705,8 +1708,8 @@ func UpdateBucket( name: "namewith\"quote", }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Op: influxdb.OpCreateBucket, Msg: "bucket name namewith\"quote is invalid. Bucket names may not include quotation marks", }, diff --git a/testing/dbrp_mapping.go b/testing/dbrp_mapping.go index 48a40cb28a6..b605cd18dae 100644 --- a/testing/dbrp_mapping.go +++ b/testing/dbrp_mapping.go @@ -6,6 +6,8 @@ import ( "sort" "testing" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" platform "github.com/influxdata/influxdb/v2" "github.com/pkg/errors" @@ -217,8 +219,8 @@ func CreateDBRPMapping( }, }, wants: wants{ - err: &platform.Error{ - Code: platform.EConflict, + err: &errors2.Error{ + Code: errors2.EConflict, Msg: "dbrp mapping already exists", }, dbrpMappings: []*platform.DBRPMapping{ @@ -515,8 +517,8 @@ func FindDBRPMappingByKey( RetentionPolicy: "retention_policyA", }, wants: wants{ - err: &platform.Error{ - Code: platform.ENotFound, + err: &errors2.Error{ + Code: errors2.ENotFound, Msg: "dbrp mapping not found", }, }, @@ -673,8 +675,8 @@ func FindDBRPMapping( filter: platform.DBRPMappingFilter{}, }, wants: wants{ - err: &platform.Error{ - Code: platform.EInvalid, + err: &errors2.Error{ + Code: errors2.EInvalid, Msg: "no filter parameters provided", }, }, diff --git a/testing/dbrp_mapping_v2.go b/testing/dbrp_mapping_v2.go index dd0c2b2be82..04cce4d6175 100644 --- a/testing/dbrp_mapping_v2.go +++ b/testing/dbrp_mapping_v2.go @@ -7,6 +7,9 @@ import ( "sort" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/dbrp" @@ -310,10 +313,10 @@ func CreateDBRPMappingV2( name: "error bucket does not exist", fields: DBRPMappingFieldsV2{ BucketSvc: &mock.BucketService{ - FindBucketByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { if id == MustIDBase16(dbrpBucket2ID) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors2.Error{ + Code: errors2.ENotFound, Msg: "bucket not found", } } @@ -340,8 +343,8 @@ func CreateDBRPMappingV2( }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors2.Error{ + Code: errors2.ENotFound, Msg: "bucket not found", }, dbrpMappings: []*influxdb.DBRPMappingV2{{ @@ -914,8 +917,8 @@ func FindDBRPMappingByIDV2( t *testing.T, ) { type args struct { - OrgID influxdb.ID - ID influxdb.ID + OrgID platform.ID + ID platform.ID } type wants struct { @@ -1456,8 +1459,8 @@ func DeleteDBRPMappingV2( t *testing.T, ) { type args struct { - OrgID influxdb.ID - ID influxdb.ID + OrgID platform.ID + ID platform.ID } type wants struct { err error diff --git a/testing/id.go b/testing/id.go index 8184dfe6bf6..6d0da503e86 100644 --- a/testing/id.go +++ b/testing/id.go @@ -1,6 +1,8 @@ package testing -import "github.com/influxdata/influxdb/v2" +import ( + "github.com/influxdata/influxdb/v2/kit/platform" +) // IDPtr returns a pointer to an influxdb.ID. -func IDPtr(id influxdb.ID) *influxdb.ID { return &id } +func IDPtr(id platform.ID) *platform.ID { return &id } diff --git a/testing/label_service.go b/testing/label_service.go index d3f5905fbcd..ca91c964d34 100644 --- a/testing/label_service.go +++ b/testing/label_service.go @@ -6,6 +6,9 @@ import ( "sort" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" @@ -34,7 +37,7 @@ var labelCmpOptions = cmp.Options{ type LabelFields struct { Labels []*influxdb.Label Mappings []*influxdb.LabelMapping - IDGenerator influxdb.IDGenerator + IDGenerator platform.IDGenerator } type labelServiceF func( @@ -143,8 +146,8 @@ func CreateLabel( }, }, }, - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Op: influxdb.OpCreateLabel, Msg: "label with name label_1 already exists", }, @@ -186,8 +189,8 @@ func CreateLabel( }, }, }, - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Op: influxdb.OpCreateLabel, Msg: "label with name tag_1 already exists", }, @@ -229,8 +232,8 @@ func CreateLabel( }, }, }, - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Op: influxdb.OpCreateLabel, Msg: "label with name TAG_1 already exists", }, @@ -426,7 +429,7 @@ func FindLabelByID( t *testing.T, ) { type args struct { - id influxdb.ID + id platform.ID } type wants struct { err error @@ -475,8 +478,8 @@ func FindLabelByID( id: MustIDBase16(labelOneID), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindLabelByID, Msg: influxdb.ErrLabelNotFound, }, @@ -504,7 +507,7 @@ func UpdateLabel( t *testing.T, ) { type args struct { - labelID influxdb.ID + labelID platform.ID update influxdb.LabelUpdate } type wants struct { @@ -580,8 +583,8 @@ func UpdateLabel( Name: "tag_2", }, }, - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Op: influxdb.OpCreateLabel, Msg: "label with name tag_1 already exists", }, @@ -622,8 +625,8 @@ func UpdateLabel( Name: "tag_2", }, }, - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Op: influxdb.OpCreateLabel, Msg: "label with name tag_1 already exists", }, @@ -749,8 +752,8 @@ func UpdateLabel( }, wants: wants{ labels: []*influxdb.Label{}, - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpUpdateLabel, Msg: influxdb.ErrLabelNotFound, }, @@ -782,7 +785,7 @@ func DeleteLabel( t *testing.T, ) { type args struct { - labelID influxdb.ID + labelID platform.ID } type wants struct { err error @@ -846,8 +849,8 @@ func DeleteLabel( Name: "Tag1", }, }, - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpDeleteLabel, Msg: influxdb.ErrLabelNotFound, }, @@ -936,8 +939,8 @@ func CreateLabelMapping( }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpDeleteLabel, Msg: influxdb.ErrLabelNotFound, }, diff --git a/testing/migration.go b/testing/migration.go index ecb695713cb..66e3be4768d 100644 --- a/testing/migration.go +++ b/testing/migration.go @@ -7,7 +7,8 @@ import ( "testing" "time" - influxdb "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kv" "github.com/influxdata/influxdb/v2/kv/migration" "go.uber.org/zap" @@ -59,17 +60,17 @@ func Migrator(t *testing.T, store kv.SchemaStore, newMigrator func(*testing.T, * if expected := []migration.Migration{ { - ID: influxdb.ID(1), + ID: platform.ID(1), Name: "migration one", State: migration.DownMigrationState, }, { - ID: influxdb.ID(2), + ID: platform.ID(2), Name: "migration two", State: migration.DownMigrationState, }, { - ID: influxdb.ID(3), + ID: platform.ID(3), Name: "migration three", State: migration.DownMigrationState, }, @@ -92,21 +93,21 @@ func Migrator(t *testing.T, store kv.SchemaStore, newMigrator func(*testing.T, * if expected := []migration.Migration{ { - ID: influxdb.ID(1), + ID: platform.ID(1), Name: "migration one", State: migration.UpMigrationState, StartedAt: ts(1), FinishedAt: ts(2), }, { - ID: influxdb.ID(2), + ID: platform.ID(2), Name: "migration two", State: migration.UpMigrationState, StartedAt: ts(3), FinishedAt: ts(4), }, { - ID: influxdb.ID(3), + ID: platform.ID(3), Name: "migration three", State: migration.UpMigrationState, StartedAt: ts(5), @@ -133,28 +134,28 @@ func Migrator(t *testing.T, store kv.SchemaStore, newMigrator func(*testing.T, * if expected := []migration.Migration{ { - ID: influxdb.ID(1), + ID: platform.ID(1), Name: "migration one", State: migration.UpMigrationState, StartedAt: ts(1), FinishedAt: ts(2), }, { - ID: influxdb.ID(2), + ID: platform.ID(2), Name: "migration two", State: migration.UpMigrationState, StartedAt: ts(3), FinishedAt: ts(4), }, { - ID: influxdb.ID(3), + ID: platform.ID(3), Name: "migration three", State: migration.UpMigrationState, StartedAt: ts(5), FinishedAt: ts(6), }, { - ID: influxdb.ID(4), + ID: platform.ID(4), Name: "migration four", State: migration.DownMigrationState, }, @@ -177,28 +178,28 @@ func Migrator(t *testing.T, store kv.SchemaStore, newMigrator func(*testing.T, * if expected := []migration.Migration{ { - ID: influxdb.ID(1), + ID: platform.ID(1), Name: "migration one", State: migration.UpMigrationState, StartedAt: ts(1), FinishedAt: ts(2), }, { - ID: influxdb.ID(2), + ID: platform.ID(2), Name: "migration two", State: migration.UpMigrationState, StartedAt: ts(3), FinishedAt: ts(4), }, { - ID: influxdb.ID(3), + ID: platform.ID(3), Name: "migration three", State: migration.UpMigrationState, StartedAt: ts(5), FinishedAt: ts(6), }, { - ID: influxdb.ID(4), + ID: platform.ID(4), Name: "migration four", State: migration.UpMigrationState, StartedAt: ts(7), @@ -229,22 +230,22 @@ func Migrator(t *testing.T, store kv.SchemaStore, newMigrator func(*testing.T, * if expected := []migration.Migration{ { - ID: influxdb.ID(1), + ID: platform.ID(1), Name: "migration one", State: migration.DownMigrationState, }, { - ID: influxdb.ID(2), + ID: platform.ID(2), Name: "migration two", State: migration.DownMigrationState, }, { - ID: influxdb.ID(3), + ID: platform.ID(3), Name: "migration three", State: migration.DownMigrationState, }, { - ID: influxdb.ID(4), + ID: platform.ID(4), Name: "migration four", State: migration.DownMigrationState, }, @@ -273,28 +274,28 @@ func Migrator(t *testing.T, store kv.SchemaStore, newMigrator func(*testing.T, * if expected := []migration.Migration{ { - ID: influxdb.ID(1), + ID: platform.ID(1), Name: "migration one", State: migration.UpMigrationState, StartedAt: ts(9), FinishedAt: ts(10), }, { - ID: influxdb.ID(2), + ID: platform.ID(2), Name: "migration two", State: migration.UpMigrationState, StartedAt: ts(11), FinishedAt: ts(12), }, { - ID: influxdb.ID(3), + ID: platform.ID(3), Name: "migration three", State: migration.UpMigrationState, StartedAt: ts(13), FinishedAt: ts(14), }, { - ID: influxdb.ID(4), + ID: platform.ID(4), Name: "migration four", State: migration.UpMigrationState, StartedAt: ts(15), diff --git a/testing/onboarding.go b/testing/onboarding.go index b48b02e11b4..c91048d5bd0 100644 --- a/testing/onboarding.go +++ b/testing/onboarding.go @@ -5,6 +5,9 @@ import ( "testing" "time" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" platform "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" @@ -29,7 +32,7 @@ var onboardCmpOptions = cmp.Options{ // OnboardingFields will include the IDGenerator, TokenGenerator // and IsOnboarding type OnboardingFields struct { - IDGenerator platform.IDGenerator + IDGenerator platform2.IDGenerator TokenGenerator platform.TokenGenerator TimeGenerator platform.TimeGenerator IsOnboarding bool @@ -63,7 +66,7 @@ func OnboardInitialUser( IsOnboarding: false, }, wants: wants{ - errCode: platform.EConflict, + errCode: errors.EConflict, }, }, { @@ -82,7 +85,7 @@ func OnboardInitialUser( }, }, wants: wants{ - errCode: platform.EEmptyValue, + errCode: errors.EEmptyValue, }, }, { @@ -101,7 +104,7 @@ func OnboardInitialUser( }, }, wants: wants{ - errCode: platform.EEmptyValue, + errCode: errors.EEmptyValue, }, }, { @@ -120,7 +123,7 @@ func OnboardInitialUser( }, }, wants: wants{ - errCode: platform.EEmptyValue, + errCode: errors.EEmptyValue, }, }, { @@ -139,7 +142,7 @@ func OnboardInitialUser( }, }, wants: wants{ - errCode: platform.EEmptyValue, + errCode: errors.EEmptyValue, }, }, { @@ -214,7 +217,7 @@ func OnboardInitialUser( t.Fatalf("expected error code '%s' got '%v'", tt.wants.errCode, err) } if err != nil && tt.wants.errCode != "" { - if code := platform.ErrorCode(err); code != tt.wants.errCode { + if code := errors.ErrorCode(err); code != tt.wants.errCode { t.Logf("Error: %v", err) t.Fatalf("expected error code to match '%s' got '%v'", tt.wants.errCode, code) } @@ -242,7 +245,7 @@ type loopIDGenerator struct { p int } -func (g *loopIDGenerator) ID() platform.ID { +func (g *loopIDGenerator) ID() platform2.ID { if g.p == len(g.s) { g.p = 0 } diff --git a/testing/organization_service.go b/testing/organization_service.go index 83ae6c3b329..4342ce5cbed 100644 --- a/testing/organization_service.go +++ b/testing/organization_service.go @@ -7,6 +7,9 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" @@ -38,8 +41,8 @@ var organizationCmpOptions = cmp.Options{ // OrganizationFields will include the IDGenerator, and organizations type OrganizationFields struct { - IDGenerator influxdb.IDGenerator - OrgBucketIDs influxdb.IDGenerator + IDGenerator platform.IDGenerator + OrgBucketIDs platform.IDGenerator Organizations []*influxdb.Organization TimeGenerator influxdb.TimeGenerator } @@ -125,7 +128,7 @@ func CreateOrganization( organizations: []*influxdb.Organization{ { Name: "name1", - ID: influxdb.ID(mock.FirstMockID), + ID: platform.ID(mock.FirstMockID), Description: "desc1", CRUDLog: influxdb.CRUDLog{ CreatedAt: time.Date(2006, 5, 4, 1, 2, 3, 0, time.UTC), @@ -161,7 +164,7 @@ func CreateOrganization( Name: "organization1", }, { - ID: influxdb.ID(mock.FirstMockID), + ID: platform.ID(mock.FirstMockID), Name: "organization2", CRUDLog: influxdb.CRUDLog{ CreatedAt: time.Date(2006, 5, 4, 1, 2, 3, 0, time.UTC), @@ -254,8 +257,8 @@ func CreateOrganization( Name: "organization1", }, }, - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Op: influxdb.OpCreateOrganization, Msg: "organization with name organization1 already exists", }, @@ -286,7 +289,7 @@ func CreateOrganization( Name: "organization1", }, { - ID: influxdb.ID(mock.FirstMockID), + ID: platform.ID(mock.FirstMockID), Name: "organization2", CRUDLog: influxdb.CRUDLog{ CreatedAt: time.Date(2006, 5, 4, 1, 2, 3, 0, time.UTC), @@ -325,7 +328,7 @@ func FindOrganizationByID( t *testing.T, ) { type args struct { - id influxdb.ID + id platform.ID } type wants struct { err error @@ -383,8 +386,8 @@ func FindOrganizationByID( }, wants: wants{ organization: nil, - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindOrganizationByID, Msg: "organization not found", }, @@ -414,7 +417,7 @@ func FindOrganizations( t *testing.T, ) { type args struct { - ID influxdb.ID + ID platform.ID name string findOptions influxdb.FindOptions } @@ -570,8 +573,8 @@ func FindOrganizations( }, wants: wants{ organizations: []*influxdb.Organization{}, - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindOrganizations, Msg: "organization not found", }, @@ -597,8 +600,8 @@ func FindOrganizations( }, wants: wants{ organizations: []*influxdb.Organization{}, - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindOrganizations, Msg: "organization name \"na\" not found", }, @@ -636,7 +639,7 @@ func DeleteOrganization( t *testing.T, ) { type args struct { - ID influxdb.ID + ID platform.ID } type wants struct { err error @@ -696,8 +699,8 @@ func DeleteOrganization( ID: MustIDBase16("1234567890654321"), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpDeleteOrganization, Msg: "organization not found", }, @@ -741,7 +744,7 @@ func FindOrganization( ) { type args struct { name string - id influxdb.ID + id platform.ID } type wants struct { @@ -786,8 +789,8 @@ func FindOrganization( name: "unknown", }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindOrganization, Msg: "organization name \"unknown\" not found", }, @@ -796,11 +799,11 @@ func FindOrganization( { name: "find organization in which no id filter matches should return no org", args: args{ - id: influxdb.ID(3), + id: platform.ID(3), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "organization not found", }, }, @@ -830,8 +833,8 @@ func FindOrganization( name: "abc", }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindOrganization, Msg: "organization name \"abc\" not found", }, @@ -848,7 +851,7 @@ func FindOrganization( if tt.args.name != "" { filter.Name = &tt.args.name } - if tt.args.id != influxdb.InvalidID() { + if tt.args.id != platform.InvalidID() { filter.ID = &tt.args.id } @@ -868,7 +871,7 @@ func UpdateOrganization( t *testing.T, ) { type args struct { - id influxdb.ID + id platform.ID name *string description *string } @@ -904,8 +907,8 @@ func UpdateOrganization( name: strPtr("changed"), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpUpdateOrganization, Msg: "organization not found", }, @@ -991,8 +994,8 @@ func UpdateOrganization( name: strPtr("organization2"), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Op: influxdb.OpUpdateOrganization, Msg: "organization with name organization2 already exists", }, diff --git a/testing/passwords.go b/testing/passwords.go index 236c7a4d7d8..45871372a07 100644 --- a/testing/passwords.go +++ b/testing/passwords.go @@ -5,12 +5,14 @@ import ( "fmt" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) // PasswordFields will include the IDGenerator, and users and their passwords. type PasswordFields struct { - IDGenerator influxdb.IDGenerator + IDGenerator platform.IDGenerator Users []*influxdb.User Passwords []string // passwords are indexed against the Users field } @@ -51,7 +53,7 @@ func SetPassword( init func(PasswordFields, *testing.T) (influxdb.PasswordsService, func()), t *testing.T) { type args struct { - user influxdb.ID + user platform.ID password string } type wants struct { @@ -144,7 +146,7 @@ func ComparePassword( init func(PasswordFields, *testing.T) (influxdb.PasswordsService, func()), t *testing.T) { type args struct { - user influxdb.ID + user platform.ID password string } type wants struct { @@ -260,7 +262,7 @@ func CompareAndSetPassword( init func(PasswordFields, *testing.T) (influxdb.PasswordsService, func()), t *testing.T) { type args struct { - user influxdb.ID + user platform.ID old string new string } diff --git a/testing/scraper_target.go b/testing/scraper_target.go index fe69981cff9..c97fc04296e 100644 --- a/testing/scraper_target.go +++ b/testing/scraper_target.go @@ -7,6 +7,9 @@ import ( "sort" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" @@ -43,7 +46,7 @@ var ( URL: "url3", ID: MustIDBase16(targetThreeID), } - newOrg = func(id influxdb.ID) *influxdb.Organization { + newOrg = func(id platform.ID) *influxdb.Organization { return &influxdb.Organization{ ID: id, Name: fmt.Sprintf("org%d", int(id)), @@ -53,7 +56,7 @@ var ( // TargetFields will include the IDGenerator, and targets type TargetFields struct { - IDGenerator influxdb.IDGenerator + IDGenerator platform.IDGenerator Targets []*influxdb.ScraperTarget Organizations []*influxdb.Organization } @@ -118,7 +121,7 @@ func AddTarget( ) { t.Helper() type args struct { - userID influxdb.ID + userID platform.ID target *influxdb.ScraperTarget } type wants struct { @@ -136,7 +139,7 @@ func AddTarget( fields: TargetFields{ IDGenerator: mock.NewIDGenerator(targetOneID, t), Targets: []*influxdb.ScraperTarget{}, - Organizations: []*influxdb.Organization{newOrg(influxdb.ID(1))}, + Organizations: []*influxdb.Organization{newOrg(platform.ID(1))}, }, args: args{ userID: MustIDBase16(threeID), @@ -165,7 +168,7 @@ func AddTarget( name: "create target with invalid org id", fields: TargetFields{ IDGenerator: mock.NewIDGenerator(targetTwoID, t), - Organizations: []*influxdb.Organization{newOrg(influxdb.ID(1))}, + Organizations: []*influxdb.Organization{newOrg(platform.ID(1))}, Targets: []*influxdb.ScraperTarget{ { Name: "name1", @@ -187,8 +190,8 @@ func AddTarget( }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "provided organization ID has invalid format", Op: influxdb.OpAddTarget, }, @@ -208,7 +211,7 @@ func AddTarget( name: "create target with invalid bucket id", fields: TargetFields{ IDGenerator: mock.NewIDGenerator(targetTwoID, t), - Organizations: []*influxdb.Organization{newOrg(influxdb.ID(1))}, + Organizations: []*influxdb.Organization{newOrg(platform.ID(1))}, Targets: []*influxdb.ScraperTarget{ { Name: "name1", @@ -230,8 +233,8 @@ func AddTarget( }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Msg: "provided bucket ID has invalid format", Op: influxdb.OpAddTarget, }, @@ -261,7 +264,7 @@ func AddTarget( ID: MustIDBase16(targetOneID), }, }, - Organizations: []*influxdb.Organization{newOrg(influxdb.ID(1)), newOrg(influxdb.ID(2))}, + Organizations: []*influxdb.Organization{newOrg(platform.ID(1)), newOrg(platform.ID(2))}, }, args: args{ userID: MustIDBase16(threeID), @@ -340,8 +343,8 @@ func ListTargets( name: "get all targets", fields: TargetFields{ Organizations: []*influxdb.Organization{ - newOrg(influxdb.ID(1)), - newOrg(influxdb.ID(2)), + newOrg(platform.ID(1)), + newOrg(platform.ID(2)), }, Targets: []*influxdb.ScraperTarget{ &target1, @@ -364,8 +367,8 @@ func ListTargets( name: "filter by name", fields: TargetFields{ Organizations: []*influxdb.Organization{ - newOrg(influxdb.ID(1)), - newOrg(influxdb.ID(2)), + newOrg(platform.ID(1)), + newOrg(platform.ID(2)), }, Targets: []*influxdb.ScraperTarget{ &target1, @@ -388,8 +391,8 @@ func ListTargets( name: "filter by id", fields: TargetFields{ Organizations: []*influxdb.Organization{ - newOrg(influxdb.ID(1)), - newOrg(influxdb.ID(2)), + newOrg(platform.ID(1)), + newOrg(platform.ID(2)), }, Targets: []*influxdb.ScraperTarget{ &target1, @@ -399,7 +402,7 @@ func ListTargets( }, args: args{ filter: influxdb.ScraperTargetFilter{ - IDs: map[influxdb.ID]bool{target2.ID: false}, + IDs: map[platform.ID]bool{target2.ID: false}, }, }, wants: wants{ @@ -412,8 +415,8 @@ func ListTargets( name: "filter targets by orgID", fields: TargetFields{ Organizations: []*influxdb.Organization{ - newOrg(influxdb.ID(1)), - newOrg(influxdb.ID(2)), + newOrg(platform.ID(1)), + newOrg(platform.ID(2)), }, Targets: []*influxdb.ScraperTarget{ &target1, @@ -437,8 +440,8 @@ func ListTargets( name: "filter targets by org name", fields: TargetFields{ Organizations: []*influxdb.Organization{ - newOrg(influxdb.ID(1)), - newOrg(influxdb.ID(2)), + newOrg(platform.ID(1)), + newOrg(platform.ID(2)), }, Targets: []*influxdb.ScraperTarget{ &target1, @@ -462,7 +465,7 @@ func ListTargets( name: "filter targets by org name not exist", fields: TargetFields{ Organizations: []*influxdb.Organization{ - newOrg(influxdb.ID(1)), + newOrg(platform.ID(1)), }, Targets: []*influxdb.ScraperTarget{ &target1, @@ -477,8 +480,8 @@ func ListTargets( }, wants: wants{ targets: []influxdb.ScraperTarget{}, - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: `organization name "org2" not found`, }, }, @@ -506,7 +509,7 @@ func GetTargetByID( ) { t.Helper() type args struct { - id influxdb.ID + id platform.ID } type wants struct { err error @@ -522,7 +525,7 @@ func GetTargetByID( { name: "basic find target by id", fields: TargetFields{ - Organizations: []*influxdb.Organization{newOrg(influxdb.ID(1))}, + Organizations: []*influxdb.Organization{newOrg(platform.ID(1))}, Targets: []*influxdb.ScraperTarget{ { ID: MustIDBase16(targetOneID), @@ -572,8 +575,8 @@ func GetTargetByID( id: MustIDBase16(threeID), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpGetTargetByID, Msg: "scraper target is not found", }, @@ -601,8 +604,8 @@ func GetTargetByID( func RemoveTarget(init func(TargetFields, *testing.T) (influxdb.ScraperTargetStoreService, string, func()), t *testing.T) { type args struct { - ID influxdb.ID - userID influxdb.ID + ID platform.ID + userID platform.ID } type wants struct { err error @@ -617,7 +620,7 @@ func RemoveTarget(init func(TargetFields, *testing.T) (influxdb.ScraperTargetSto { name: "delete targets using exist id", fields: TargetFields{ - Organizations: []*influxdb.Organization{newOrg(influxdb.ID(1))}, + Organizations: []*influxdb.Organization{newOrg(platform.ID(1))}, Targets: []*influxdb.ScraperTarget{ { ID: MustIDBase16(targetOneID), @@ -648,7 +651,7 @@ func RemoveTarget(init func(TargetFields, *testing.T) (influxdb.ScraperTargetSto { name: "delete targets using id that does not exist", fields: TargetFields{ - Organizations: []*influxdb.Organization{newOrg(influxdb.ID(1))}, + Organizations: []*influxdb.Organization{newOrg(platform.ID(1))}, Targets: []*influxdb.ScraperTarget{ { ID: MustIDBase16(targetOneID), @@ -667,8 +670,8 @@ func RemoveTarget(init func(TargetFields, *testing.T) (influxdb.ScraperTargetSto userID: MustIDBase16(threeID), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpRemoveTarget, Msg: "scraper target is not found", }, @@ -713,8 +716,8 @@ func UpdateTarget( ) { type args struct { url string - userID influxdb.ID - id influxdb.ID + userID platform.ID + id platform.ID } type wants struct { err error @@ -730,7 +733,7 @@ func UpdateTarget( { name: "update url with blank id", fields: TargetFields{ - Organizations: []*influxdb.Organization{newOrg(influxdb.ID(1))}, + Organizations: []*influxdb.Organization{newOrg(platform.ID(1))}, Targets: []*influxdb.ScraperTarget{ { ID: MustIDBase16(targetOneID), @@ -750,8 +753,8 @@ func UpdateTarget( url: "changed", }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EInvalid, + err: &errors.Error{ + Code: errors.EInvalid, Op: influxdb.OpUpdateTarget, Msg: "provided scraper target ID has invalid format", }, @@ -760,7 +763,7 @@ func UpdateTarget( { name: "update url with non exist id", fields: TargetFields{ - Organizations: []*influxdb.Organization{newOrg(influxdb.ID(1))}, + Organizations: []*influxdb.Organization{newOrg(platform.ID(1))}, Targets: []*influxdb.ScraperTarget{ { ID: MustIDBase16(targetOneID), @@ -781,8 +784,8 @@ func UpdateTarget( url: "changed", }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpUpdateTarget, Msg: "scraper target is not found", }, @@ -791,7 +794,7 @@ func UpdateTarget( { name: "update url", fields: TargetFields{ - Organizations: []*influxdb.Organization{newOrg(influxdb.ID(1))}, + Organizations: []*influxdb.Organization{newOrg(platform.ID(1))}, Targets: []*influxdb.ScraperTarget{ { ID: MustIDBase16(targetOneID), diff --git a/testing/secret.go b/testing/secret.go index 76094b9745c..5e071e50cf0 100644 --- a/testing/secret.go +++ b/testing/secret.go @@ -6,6 +6,9 @@ import ( "sort" "testing" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" platform "github.com/influxdata/influxdb/v2" ) @@ -23,7 +26,7 @@ var secretCmpOptions = cmp.Options{ // A secret is a comparable data structure that is used for testing type Secret struct { - OrganizationID platform.ID + OrganizationID platform2.ID Env map[string]string } @@ -85,7 +88,7 @@ func LoadSecret( t *testing.T, ) { type args struct { - orgID platform.ID + orgID platform2.ID key string } type wants struct { @@ -104,7 +107,7 @@ func LoadSecret( fields: SecretServiceFields{ Secrets: []Secret{ { - OrganizationID: platform.ID(1), + OrganizationID: platform2.ID(1), Env: map[string]string{ "api_key": "abc123xyz", }, @@ -112,7 +115,7 @@ func LoadSecret( }, }, args: args{ - orgID: platform.ID(1), + orgID: platform2.ID(1), key: "api_key", }, wants: wants{ @@ -151,7 +154,7 @@ func PutSecret( t *testing.T, ) { type args struct { - orgID platform.ID + orgID platform2.ID key string value string } @@ -169,7 +172,7 @@ func PutSecret( name: "put secret", fields: SecretServiceFields{}, args: args{ - orgID: platform.ID(1), + orgID: platform2.ID(1), key: "api_key", value: "abc123xyz", }, @@ -212,7 +215,7 @@ func PutSecrets( t *testing.T, ) { type args struct { - orgID platform.ID + orgID platform2.ID secrets map[string]string } type wants struct { @@ -231,7 +234,7 @@ func PutSecrets( fields: SecretServiceFields{ Secrets: []Secret{ { - OrganizationID: platform.ID(1), + OrganizationID: platform2.ID(1), Env: map[string]string{ "api_key": "abc123xyz", }, @@ -239,7 +242,7 @@ func PutSecrets( }, }, args: args{ - orgID: platform.ID(1), + orgID: platform2.ID(1), secrets: map[string]string{ "api_key2": "abc123xyz", "batman": "potato", @@ -297,7 +300,7 @@ func PatchSecrets( t *testing.T, ) { type args struct { - orgID platform.ID + orgID platform2.ID secrets map[string]string } type wants struct { @@ -316,7 +319,7 @@ func PatchSecrets( fields: SecretServiceFields{ Secrets: []Secret{ { - OrganizationID: platform.ID(1), + OrganizationID: platform2.ID(1), Env: map[string]string{ "api_key": "abc123xyz", }, @@ -324,7 +327,7 @@ func PatchSecrets( }, }, args: args{ - orgID: platform.ID(1), + orgID: platform2.ID(1), secrets: map[string]string{ "api_key2": "abc123xyz", "batman": "potato", @@ -357,7 +360,7 @@ func PatchSecrets( for k, v := range tt.args.secrets { val, err := s.LoadSecret(ctx, tt.args.orgID, k) if err != nil { - if platform.ErrorCode(err) == platform.EMethodNotAllowed { + if errors.ErrorCode(err) == errors.EMethodNotAllowed { // skip value checking for http service testing break } @@ -387,7 +390,7 @@ func GetSecretKeys( t *testing.T, ) { type args struct { - orgID platform.ID + orgID platform2.ID } type wants struct { keys []string @@ -405,13 +408,13 @@ func GetSecretKeys( fields: SecretServiceFields{ Secrets: []Secret{ { - OrganizationID: platform.ID(1), + OrganizationID: platform2.ID(1), Env: map[string]string{ "api_key": "abc123xyz", }, }, { - OrganizationID: platform.ID(2), + OrganizationID: platform2.ID(2), Env: map[string]string{ "api_key": "zyx321cba", }, @@ -419,7 +422,7 @@ func GetSecretKeys( }, }, args: args{ - orgID: platform.ID(1), + orgID: platform2.ID(1), }, wants: wants{ keys: []string{"api_key"}, @@ -457,7 +460,7 @@ func DeleteSecrets( t *testing.T, ) { type args struct { - orgID platform.ID + orgID platform2.ID keys []string } type wants struct { @@ -476,7 +479,7 @@ func DeleteSecrets( fields: SecretServiceFields{ Secrets: []Secret{ { - OrganizationID: platform.ID(1), + OrganizationID: platform2.ID(1), Env: map[string]string{ "api_key": "abc123xyz", "api_key2": "potato", @@ -486,7 +489,7 @@ func DeleteSecrets( }, }, args: args{ - orgID: platform.ID(1), + orgID: platform2.ID(1), keys: []string{"api_key2", "batman"}, }, wants: wants{ diff --git a/testing/session.go b/testing/session.go index 50f21fc3ba4..b40f3bbd26b 100644 --- a/testing/session.go +++ b/testing/session.go @@ -7,6 +7,9 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/influxdata/influxdb/v2" @@ -39,7 +42,7 @@ func sessionCompareOptions(ignore ...string) cmp.Options { // SessionFields will include the IDGenerator, TokenGenerator, Sessions, and Users type SessionFields struct { - IDGenerator influxdb.IDGenerator + IDGenerator platform.IDGenerator TokenGenerator influxdb.TokenGenerator Sessions []*influxdb.Session Users []*influxdb.User @@ -194,8 +197,8 @@ func FindSession( key: "abc123xyz", }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindSession, Msg: influxdb.ErrSessionNotFound, }, @@ -394,8 +397,8 @@ func RenewSession( expireAt: time.Date(2031, 9, 26, 0, 0, 10, 0, time.UTC), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EInternal, + err: &errors.Error{ + Code: errors.EInternal, Msg: "session is nil", Op: influxdb.OpRenewSession, }, diff --git a/testing/source.go b/testing/source.go index 5f0cf03e133..6605ccd204f 100644 --- a/testing/source.go +++ b/testing/source.go @@ -6,6 +6,9 @@ import ( "sort" "testing" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" platform "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" @@ -34,7 +37,7 @@ var sourceCmpOptions = cmp.Options{ // SourceFields will include the IDGenerator, and sources type SourceFields struct { - IDGenerator platform.IDGenerator + IDGenerator platform2.IDGenerator Sources []*platform.Source } @@ -113,7 +116,7 @@ func FindSourceByID( t *testing.T, ) { type args struct { - id platform.ID + id platform2.ID } type wants struct { err error @@ -267,7 +270,7 @@ func DeleteSource( t *testing.T, ) { type args struct { - id platform.ID + id platform2.ID } type wants struct { err error @@ -317,8 +320,8 @@ func DeleteSource( id: MustIDBase16(defaultSourceID), }, wants: wants{ - err: &platform.Error{ - Code: platform.EForbidden, + err: &errors.Error{ + Code: errors.EForbidden, Op: platform.OpDeleteSource, Msg: "cannot delete autogen source", }, diff --git a/testing/tenant.go b/testing/tenant.go index 6e956d93e45..16e23ab63e9 100644 --- a/testing/tenant.go +++ b/testing/tenant.go @@ -6,14 +6,16 @@ import ( "strings" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" ) type TenantFields struct { - OrgIDGenerator influxdb.IDGenerator - BucketIDGenerator influxdb.IDGenerator + OrgIDGenerator platform.IDGenerator + BucketIDGenerator platform.IDGenerator Users []*influxdb.User Passwords []string // passwords are indexed against the Users field UserResourceMappings []*influxdb.UserResourceMapping diff --git a/testing/user_resource_mapping_service.go b/testing/user_resource_mapping_service.go index 3acc4169187..f5c0dfd0005 100644 --- a/testing/user_resource_mapping_service.go +++ b/testing/user_resource_mapping_service.go @@ -7,6 +7,8 @@ import ( "sort" "testing" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/google/go-cmp/cmp" platform "github.com/influxdata/influxdb/v2" ) @@ -212,8 +214,8 @@ func DeleteUserResourceMapping( t *testing.T, ) { type args struct { - resourceID platform.ID - userID platform.ID + resourceID platform2.ID + userID platform2.ID } type wants struct { err error diff --git a/testing/user_service.go b/testing/user_service.go index 77af80475cd..f7dac0c6e07 100644 --- a/testing/user_service.go +++ b/testing/user_service.go @@ -6,6 +6,9 @@ import ( "sort" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" @@ -41,7 +44,7 @@ var userCmpOptions = cmp.Options{ // UserFields will include the IDGenerator, and users type UserFields struct { - IDGenerator influxdb.IDGenerator + IDGenerator platform.IDGenerator Users []*influxdb.User } @@ -170,7 +173,7 @@ func CreateUser( name: "names should be unique", fields: UserFields{ IDGenerator: &mock.IDGenerator{ - IDFn: func() influxdb.ID { + IDFn: func() platform.ID { return MustIDBase16(userOneID) }, }, @@ -195,8 +198,8 @@ func CreateUser( Status: influxdb.Active, }, }, - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Op: influxdb.OpCreateUser, Msg: "user with name user1 already exists", }, @@ -234,7 +237,7 @@ func FindUserByID( t *testing.T, ) { type args struct { - id influxdb.ID + id platform.ID } type wants struct { err error @@ -294,8 +297,8 @@ func FindUserByID( id: MustIDBase16(threeID), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindUserByID, Msg: "user not found", }, @@ -325,7 +328,7 @@ func FindUsers( t *testing.T, ) { type args struct { - ID influxdb.ID + ID platform.ID name string } @@ -447,8 +450,8 @@ func FindUsers( ID: MustIDBase16(threeID), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindUsers, Msg: "user not found", }, @@ -472,8 +475,8 @@ func FindUsers( name: "no_exist", }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindUsers, Msg: "user not found", }, @@ -511,7 +514,7 @@ func DeleteUser( t *testing.T, ) { type args struct { - ID influxdb.ID + ID platform.ID } type wants struct { err error @@ -573,8 +576,8 @@ func DeleteUser( ID: MustIDBase16(userThreeID), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpDeleteUser, Msg: "user not found", }, @@ -681,7 +684,7 @@ func FindUser( }, args: args{ filter: influxdb.UserFilter{ - ID: func(id influxdb.ID) *influxdb.ID { return &id }(MustIDBase16(userOneID)), + ID: func(id platform.ID) *platform.ID { return &id }(MustIDBase16(userOneID)), }, }, wants: wants{ @@ -703,8 +706,8 @@ func FindUser( }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "user not found", Op: influxdb.OpFindUser, }, @@ -717,12 +720,12 @@ func FindUser( }, args: args{ filter: influxdb.UserFilter{ - ID: func(id influxdb.ID) *influxdb.ID { return &id }(MustIDBase16(userOneID)), + ID: func(id platform.ID) *platform.ID { return &id }(MustIDBase16(userOneID)), }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "user not found", Op: influxdb.OpFindUser, }, @@ -746,7 +749,7 @@ func FindUser( }, args: args{ filter: influxdb.UserFilter{ - ID: func(id influxdb.ID) *influxdb.ID { return &id }(MustIDBase16(userOneID)), + ID: func(id platform.ID) *platform.ID { return &id }(MustIDBase16(userOneID)), Name: func(s string) *string { return &s }("xyz"), }, }, @@ -772,8 +775,8 @@ func FindUser( filter: influxdb.UserFilter{}, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "user not found", Op: influxdb.OpFindUser, }, @@ -791,13 +794,13 @@ func FindUser( }, args: args{ filter: influxdb.UserFilter{ - ID: func(id influxdb.ID) *influxdb.ID { return &id }(MustIDBase16(userOneID)), + ID: func(id platform.ID) *platform.ID { return &id }(MustIDBase16(userOneID)), Name: func(s string) *string { return &s }("xyz"), }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Msg: "user not found", Op: influxdb.OpFindUser, }, @@ -827,7 +830,7 @@ func UpdateUser( ) { type args struct { name string - id influxdb.ID + id platform.ID status string } type wants struct { @@ -944,8 +947,8 @@ func UpdateUser( name: "changed", }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpUpdateUser, Msg: "user not found", }, @@ -1026,8 +1029,8 @@ func UpdateUser_IndexHygiene( _, oerr := s.FindUser(ctx, influxdb.UserFilter{ Name: &oldUserName, }) - ErrorsEqual(t, oerr, &influxdb.Error{ - Code: influxdb.ENotFound, + ErrorsEqual(t, oerr, &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindUser, Msg: "user not found", }) diff --git a/testing/util.go b/testing/util.go index 4f21916d056..7eb6ebe9324 100644 --- a/testing/util.go +++ b/testing/util.go @@ -5,6 +5,9 @@ import ( "strings" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -31,14 +34,14 @@ func ErrorsEqual(t *testing.T, actual, expected error) { t.Errorf("expected error %s but received nil", expected.Error()) } - if influxdb.ErrorCode(expected) != influxdb.ErrorCode(actual) { + if errors.ErrorCode(expected) != errors.ErrorCode(actual) { t.Logf("\nexpected: %v\nactual: %v\n\n", expected, actual) - t.Errorf("expected error code %q but received %q", influxdb.ErrorCode(expected), influxdb.ErrorCode(actual)) + t.Errorf("expected error code %q but received %q", errors.ErrorCode(expected), errors.ErrorCode(actual)) } - if influxdb.ErrorMessage(expected) != influxdb.ErrorMessage(actual) { + if errors.ErrorMessage(expected) != errors.ErrorMessage(actual) { t.Logf("\nexpected: %v\nactual: %v\n\n", expected, actual) - t.Errorf("expected error message %q but received %q", influxdb.ErrorMessage(expected), influxdb.ErrorMessage(actual)) + t.Errorf("expected error message %q but received %q", errors.ErrorMessage(expected), errors.ErrorMessage(actual)) } } @@ -49,13 +52,13 @@ func FloatPtr(f float64) *float64 { return p } -func idPtr(id influxdb.ID) *influxdb.ID { +func idPtr(id platform.ID) *platform.ID { return &id } // MustIDBase16 is an helper to ensure a correct ID is built during testing. -func MustIDBase16(s string) influxdb.ID { - id, err := influxdb.IDFromString(s) +func MustIDBase16(s string) platform.ID { + id, err := platform.IDFromString(s) if err != nil { panic(err) } @@ -63,7 +66,7 @@ func MustIDBase16(s string) influxdb.ID { } // MustIDBase16Ptr is an helper to ensure a correct ID ptr ref is built during testing. -func MustIDBase16Ptr(s string) *influxdb.ID { +func MustIDBase16Ptr(s string) *platform.ID { id := MustIDBase16(s) return &id } @@ -100,7 +103,7 @@ func MustCreateMappings(ctx context.Context, svc influxdb.UserResourceMappingSer } } -func MustMakeUsersOrgOwner(ctx context.Context, svc influxdb.UserResourceMappingService, oid influxdb.ID, uids ...influxdb.ID) { +func MustMakeUsersOrgOwner(ctx context.Context, svc influxdb.UserResourceMappingService, oid platform.ID, uids ...platform.ID) { ms := make([]*influxdb.UserResourceMapping, len(uids)) for i, uid := range uids { ms[i] = &influxdb.UserResourceMapping{ @@ -113,7 +116,7 @@ func MustMakeUsersOrgOwner(ctx context.Context, svc influxdb.UserResourceMapping MustCreateMappings(ctx, svc, ms...) } -func MustMakeUsersOrgMember(ctx context.Context, svc influxdb.UserResourceMappingService, oid influxdb.ID, uids ...influxdb.ID) { +func MustMakeUsersOrgMember(ctx context.Context, svc influxdb.UserResourceMappingService, oid platform.ID, uids ...platform.ID) { ms := make([]*influxdb.UserResourceMapping, len(uids)) for i, uid := range uids { ms[i] = &influxdb.UserResourceMapping{ @@ -126,7 +129,7 @@ func MustMakeUsersOrgMember(ctx context.Context, svc influxdb.UserResourceMappin MustCreateMappings(ctx, svc, ms...) } -func MustNewPermissionAtID(id influxdb.ID, a influxdb.Action, rt influxdb.ResourceType, orgID influxdb.ID) *influxdb.Permission { +func MustNewPermissionAtID(id platform.ID, a influxdb.Action, rt influxdb.ResourceType, orgID platform.ID) *influxdb.Permission { perm, err := influxdb.NewPermissionAtID(id, a, rt, orgID) if err != nil { panic(err) @@ -134,7 +137,7 @@ func MustNewPermissionAtID(id influxdb.ID, a influxdb.Action, rt influxdb.Resour return perm } -func influxErrsEqual(t *testing.T, expected *influxdb.Error, actual error) { +func influxErrsEqual(t *testing.T, expected *errors.Error, actual error) { t.Helper() if expected != nil { @@ -149,7 +152,7 @@ func influxErrsEqual(t *testing.T, expected *influxdb.Error, actual error) { require.NoError(t, actual) return } - iErr, ok := actual.(*influxdb.Error) + iErr, ok := actual.(*errors.Error) require.True(t, ok) assert.Equal(t, expected.Code, iErr.Code) assert.Truef(t, strings.HasPrefix(iErr.Error(), expected.Error()), "expected: %s got err: %s", expected.Error(), actual.Error()) diff --git a/testing/variable.go b/testing/variable.go index 33db4f1d196..50b79048108 100644 --- a/testing/variable.go +++ b/testing/variable.go @@ -8,6 +8,9 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/google/go-cmp/cmp" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" @@ -42,7 +45,7 @@ var variableCmpOptions = cmp.Options{ // VariableFields defines fields for a variable test type VariableFields struct { Variables []*influxdb.Variable - IDGenerator influxdb.IDGenerator + IDGenerator platform.IDGenerator TimeGenerator influxdb.TimeGenerator } @@ -111,7 +114,7 @@ func TrimWhitespace(init func(VariableFields, *testing.T) (influxdb.VariableServ variable *influxdb.Variable } type wants struct { - err *influxdb.Error + err *errors.Error variables []*influxdb.Variable } @@ -126,7 +129,7 @@ func TrimWhitespace(init func(VariableFields, *testing.T) (influxdb.VariableServ name: "trimwhitespace", fields: VariableFields{ IDGenerator: &mock.IDGenerator{ - IDFn: func() influxdb.ID { + IDFn: func() platform.ID { return MustIDBase16(idA) }, }, @@ -134,7 +137,7 @@ func TrimWhitespace(init func(VariableFields, *testing.T) (influxdb.VariableServ Variables: []*influxdb.Variable{ { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(3), + OrganizationID: platform.ID(3), Name: "existing-variable", Selected: []string{"b"}, Arguments: &influxdb.VariableArguments{ @@ -147,7 +150,7 @@ func TrimWhitespace(init func(VariableFields, *testing.T) (influxdb.VariableServ args: args{ variable: &influxdb.Variable{ ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(3), + OrganizationID: platform.ID(3), Name: " existing-variable ", Selected: []string{"a"}, Arguments: &influxdb.VariableArguments{ @@ -161,14 +164,14 @@ func TrimWhitespace(init func(VariableFields, *testing.T) (influxdb.VariableServ }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Msg: "variable is not unique", }, variables: []*influxdb.Variable{ { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(3), + OrganizationID: platform.ID(3), Name: "existing-variable", Selected: []string{"b"}, Arguments: &influxdb.VariableArguments{ @@ -207,7 +210,7 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ variable *influxdb.Variable } type wants struct { - err *influxdb.Error + err *errors.Error variables []*influxdb.Variable } @@ -221,7 +224,7 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ name: "basic create with missing id", fields: VariableFields{ IDGenerator: &mock.IDGenerator{ - IDFn: func() influxdb.ID { + IDFn: func() platform.ID { return MustIDBase16(idD) }, }, @@ -229,14 +232,14 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ Variables: []*influxdb.Variable{ { ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(1), + OrganizationID: platform.ID(1), Name: "already there", }, }, }, args: args{ variable: &influxdb.Variable{ - OrganizationID: influxdb.ID(3), + OrganizationID: platform.ID(3), Name: "basic variable", Selected: []string{"a"}, Arguments: &influxdb.VariableArguments{ @@ -249,12 +252,12 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ variables: []*influxdb.Variable{ { ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(1), + OrganizationID: platform.ID(1), Name: "already there", }, { ID: MustIDBase16(idD), - OrganizationID: influxdb.ID(3), + OrganizationID: platform.ID(3), Name: "basic variable", Selected: []string{"a"}, Arguments: &influxdb.VariableArguments{ @@ -273,7 +276,7 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ name: "creating a variable assigns the variable an id and adds it to the store", fields: VariableFields{ IDGenerator: &mock.IDGenerator{ - IDFn: func() influxdb.ID { + IDFn: func() platform.ID { return MustIDBase16(idA) }, }, @@ -281,7 +284,7 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ Variables: []*influxdb.Variable{ { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(3), + OrganizationID: platform.ID(3), Name: "existing-variable", Selected: []string{"b"}, Arguments: &influxdb.VariableArguments{ @@ -294,7 +297,7 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ args: args{ variable: &influxdb.Variable{ ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(3), + OrganizationID: platform.ID(3), Name: "MY-variable", Selected: []string{"a"}, Arguments: &influxdb.VariableArguments{ @@ -312,7 +315,7 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ variables: []*influxdb.Variable{ { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(3), + OrganizationID: platform.ID(3), Name: "existing-variable", Selected: []string{"b"}, Arguments: &influxdb.VariableArguments{ @@ -322,7 +325,7 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ }, { ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(3), + OrganizationID: platform.ID(3), Name: "MY-variable", Selected: []string{"a"}, Arguments: &influxdb.VariableArguments{ @@ -341,7 +344,7 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ name: "cant create a new variable with a name that exists", fields: VariableFields{ IDGenerator: &mock.IDGenerator{ - IDFn: func() influxdb.ID { + IDFn: func() platform.ID { return MustIDBase16(idA) }, }, @@ -376,8 +379,8 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Msg: "variable is not unique", }, variables: []*influxdb.Variable{ @@ -398,7 +401,7 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ name: "variable names should be unique and case-insensitive", fields: VariableFields{ IDGenerator: &mock.IDGenerator{ - IDFn: func() influxdb.ID { + IDFn: func() platform.ID { return MustIDBase16(idA) }, }, @@ -406,7 +409,7 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ Variables: []*influxdb.Variable{ { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(3), + OrganizationID: platform.ID(3), Name: "existing-variable", Selected: []string{"b"}, Arguments: &influxdb.VariableArguments{ @@ -419,7 +422,7 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ args: args{ variable: &influxdb.Variable{ ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(3), + OrganizationID: platform.ID(3), Name: "EXISTING-variable", Selected: []string{"a"}, Arguments: &influxdb.VariableArguments{ @@ -433,14 +436,14 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Msg: "variable is not unique for key ", }, variables: []*influxdb.Variable{ { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(3), + OrganizationID: platform.ID(3), Name: "existing-variable", Selected: []string{"b"}, Arguments: &influxdb.VariableArguments{ @@ -455,7 +458,7 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ name: "cant create a new variable when variable name exists with a different type", fields: VariableFields{ IDGenerator: &mock.IDGenerator{ - IDFn: func() influxdb.ID { + IDFn: func() platform.ID { return MustIDBase16(idA) }, }, @@ -463,7 +466,7 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ Variables: []*influxdb.Variable{ { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(3), + OrganizationID: platform.ID(3), Name: "existing-variable", Selected: []string{"b"}, Arguments: &influxdb.VariableArguments{ @@ -476,7 +479,7 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ args: args{ variable: &influxdb.Variable{ ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(3), + OrganizationID: platform.ID(3), Name: "existing-variable", Selected: []string{"a"}, Arguments: &influxdb.VariableArguments{ @@ -490,14 +493,14 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Msg: "variable is not unique", }, variables: []*influxdb.Variable{ { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(3), + OrganizationID: platform.ID(3), Name: "existing-variable", Selected: []string{"b"}, Arguments: &influxdb.VariableArguments{ @@ -533,10 +536,10 @@ func CreateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ // FindVariableByID tests influxdb.VariableService FindVariableByID interface method func FindVariableByID(init func(VariableFields, *testing.T) (influxdb.VariableService, string, func()), t *testing.T) { type args struct { - id influxdb.ID + id platform.ID } type wants struct { - err *influxdb.Error + err *errors.Error variable *influxdb.Variable } @@ -552,7 +555,7 @@ func FindVariableByID(init func(VariableFields, *testing.T) (influxdb.VariableSe Variables: []*influxdb.Variable{ { ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(5), + OrganizationID: platform.ID(5), Name: "existing-variable-a", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -565,7 +568,7 @@ func FindVariableByID(init func(VariableFields, *testing.T) (influxdb.VariableSe }, { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(5), + OrganizationID: platform.ID(5), Name: "existing-variable-b", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -585,7 +588,7 @@ func FindVariableByID(init func(VariableFields, *testing.T) (influxdb.VariableSe err: nil, variable: &influxdb.Variable{ ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(5), + OrganizationID: platform.ID(5), Name: "existing-variable-b", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -607,8 +610,8 @@ func FindVariableByID(init func(VariableFields, *testing.T) (influxdb.VariableSe id: MustIDBase16(idA), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpFindVariableByID, Msg: influxdb.ErrVariableNotFound, }, @@ -628,7 +631,7 @@ func FindVariableByID(init func(VariableFields, *testing.T) (influxdb.VariableSe if tt.wants.err == nil { require.NoError(t, err) } - iErr, ok := err.(*influxdb.Error) + iErr, ok := err.(*errors.Error) require.True(t, ok) assert.Equal(t, iErr.Code, tt.wants.err.Code) assert.Equal(t, strings.HasPrefix(iErr.Error(), tt.wants.err.Error()), true) @@ -647,7 +650,7 @@ func FindVariables(init func(VariableFields, *testing.T) (influxdb.VariableServi // todo(leodido) type args struct { // todo(leodido) > use VariableFilter as arg - orgID *influxdb.ID + orgID *platform.ID findOpts influxdb.FindOptions } type wants struct { @@ -679,7 +682,7 @@ func FindVariables(init func(VariableFields, *testing.T) (influxdb.VariableServi Variables: []*influxdb.Variable{ { ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(22), + OrganizationID: platform.ID(22), Name: "a", CRUDLog: influxdb.CRUDLog{ CreatedAt: fakeDate, @@ -688,7 +691,7 @@ func FindVariables(init func(VariableFields, *testing.T) (influxdb.VariableServi }, { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(22), + OrganizationID: platform.ID(22), Name: "b", CRUDLog: influxdb.CRUDLog{ CreatedAt: fakeDate, @@ -704,7 +707,7 @@ func FindVariables(init func(VariableFields, *testing.T) (influxdb.VariableServi variables: []*influxdb.Variable{ { ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(22), + OrganizationID: platform.ID(22), Name: "a", CRUDLog: influxdb.CRUDLog{ CreatedAt: fakeDate, @@ -713,7 +716,7 @@ func FindVariables(init func(VariableFields, *testing.T) (influxdb.VariableServi }, { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(22), + OrganizationID: platform.ID(22), Name: "b", CRUDLog: influxdb.CRUDLog{ CreatedAt: fakeDate, @@ -729,7 +732,7 @@ func FindVariables(init func(VariableFields, *testing.T) (influxdb.VariableServi Variables: []*influxdb.Variable{ { ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(22), + OrganizationID: platform.ID(22), Name: "a", CRUDLog: influxdb.CRUDLog{ CreatedAt: fakeDate, @@ -738,7 +741,7 @@ func FindVariables(init func(VariableFields, *testing.T) (influxdb.VariableServi }, { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(22), + OrganizationID: platform.ID(22), Name: "b", CRUDLog: influxdb.CRUDLog{ CreatedAt: fakeDate, @@ -749,7 +752,7 @@ func FindVariables(init func(VariableFields, *testing.T) (influxdb.VariableServi }, args: args{ findOpts: influxdb.DefaultVariableFindOptions, - orgID: idPtr(influxdb.ID(1)), + orgID: idPtr(platform.ID(1)), }, wants: wants{ variables: []*influxdb.Variable{}, @@ -761,7 +764,7 @@ func FindVariables(init func(VariableFields, *testing.T) (influxdb.VariableServi Variables: []*influxdb.Variable{ { ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(1), + OrganizationID: platform.ID(1), Name: "a", CRUDLog: influxdb.CRUDLog{ CreatedAt: fakeDate, @@ -770,7 +773,7 @@ func FindVariables(init func(VariableFields, *testing.T) (influxdb.VariableServi }, { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(22), + OrganizationID: platform.ID(22), Name: "b", CRUDLog: influxdb.CRUDLog{ CreatedAt: fakeDate, @@ -779,7 +782,7 @@ func FindVariables(init func(VariableFields, *testing.T) (influxdb.VariableServi }, { ID: MustIDBase16(idC), - OrganizationID: influxdb.ID(2), + OrganizationID: platform.ID(2), Name: "c", CRUDLog: influxdb.CRUDLog{ CreatedAt: fakeDate, @@ -788,7 +791,7 @@ func FindVariables(init func(VariableFields, *testing.T) (influxdb.VariableServi }, { ID: MustIDBase16(idD), - OrganizationID: influxdb.ID(22), + OrganizationID: platform.ID(22), Name: "d", CRUDLog: influxdb.CRUDLog{ CreatedAt: fakeDate, @@ -799,13 +802,13 @@ func FindVariables(init func(VariableFields, *testing.T) (influxdb.VariableServi }, args: args{ findOpts: influxdb.DefaultVariableFindOptions, - orgID: idPtr(influxdb.ID(22)), + orgID: idPtr(platform.ID(22)), }, wants: wants{ variables: []*influxdb.Variable{ { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(22), + OrganizationID: platform.ID(22), Name: "b", CRUDLog: influxdb.CRUDLog{ CreatedAt: fakeDate, @@ -814,7 +817,7 @@ func FindVariables(init func(VariableFields, *testing.T) (influxdb.VariableServi }, { ID: MustIDBase16(idD), - OrganizationID: influxdb.ID(22), + OrganizationID: platform.ID(22), Name: "d", CRUDLog: influxdb.CRUDLog{ CreatedAt: fakeDate, @@ -852,11 +855,11 @@ func FindVariables(init func(VariableFields, *testing.T) (influxdb.VariableServi // UpdateVariable tests influxdb.VariableService UpdateVariable interface method func UpdateVariable(init func(VariableFields, *testing.T) (influxdb.VariableService, string, func()), t *testing.T) { type args struct { - id influxdb.ID + id platform.ID update *influxdb.VariableUpdate } type wants struct { - err *influxdb.Error + err *errors.Error variables []*influxdb.Variable } @@ -873,7 +876,7 @@ func UpdateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ Variables: []*influxdb.Variable{ { ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(7), + OrganizationID: platform.ID(7), Name: "existing-variable-a", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -886,7 +889,7 @@ func UpdateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ }, { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(7), + OrganizationID: platform.ID(7), Name: "existing-variable-b", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -910,7 +913,7 @@ func UpdateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ variables: []*influxdb.Variable{ { ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(7), + OrganizationID: platform.ID(7), Name: "existing-variable-a", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -923,7 +926,7 @@ func UpdateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ }, { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(7), + OrganizationID: platform.ID(7), Name: "new-variable-b-name", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -949,10 +952,10 @@ func UpdateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ }, }, wants: wants{ - err: &influxdb.Error{ + err: &errors.Error{ Op: influxdb.OpUpdateVariable, Msg: influxdb.ErrVariableNotFound, - Code: influxdb.ENotFound, + Code: errors.ENotFound, }, variables: []*influxdb.Variable{}, }, @@ -964,7 +967,7 @@ func UpdateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ Variables: []*influxdb.Variable{ { ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(7), + OrganizationID: platform.ID(7), Name: "variable-a", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -977,7 +980,7 @@ func UpdateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ }, { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(7), + OrganizationID: platform.ID(7), Name: "variable-b", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -997,14 +1000,14 @@ func UpdateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Msg: "variable entity update conflicts with an existing entity", }, variables: []*influxdb.Variable{ { ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(7), + OrganizationID: platform.ID(7), Name: "variable-a", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -1017,7 +1020,7 @@ func UpdateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ }, { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(7), + OrganizationID: platform.ID(7), Name: "variable-b", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -1038,7 +1041,7 @@ func UpdateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ Variables: []*influxdb.Variable{ { ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(7), + OrganizationID: platform.ID(7), Name: "variable-a", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -1051,7 +1054,7 @@ func UpdateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ }, { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(7), + OrganizationID: platform.ID(7), Name: "variable-b", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -1071,14 +1074,14 @@ func UpdateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ }, }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.EConflict, + err: &errors.Error{ + Code: errors.EConflict, Msg: "variable entity update conflicts with an existing entity", }, variables: []*influxdb.Variable{ { ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(7), + OrganizationID: platform.ID(7), Name: "variable-a", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -1091,7 +1094,7 @@ func UpdateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ }, { ID: MustIDBase16(idB), - OrganizationID: influxdb.ID(7), + OrganizationID: platform.ID(7), Name: "variable-b", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -1139,11 +1142,11 @@ func UpdateVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ // ReplaceVariable tests influxdb.VariableService ReplaceVariable interface method func ReplaceVariable(init func(VariableFields, *testing.T) (influxdb.VariableService, string, func()), t *testing.T) { type args struct { - id influxdb.ID + id platform.ID newVariable *influxdb.Variable } type wants struct { - err *influxdb.Error + err *errors.Error variables []*influxdb.Variable } @@ -1160,7 +1163,7 @@ func ReplaceVariable(init func(VariableFields, *testing.T) (influxdb.VariableSer Variables: []*influxdb.Variable{ { ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(7), + OrganizationID: platform.ID(7), Name: "existing-variable", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -1177,7 +1180,7 @@ func ReplaceVariable(init func(VariableFields, *testing.T) (influxdb.VariableSer id: MustIDBase16(idB), newVariable: &influxdb.Variable{ ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(7), + OrganizationID: platform.ID(7), Name: "renamed-variable", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -1194,7 +1197,7 @@ func ReplaceVariable(init func(VariableFields, *testing.T) (influxdb.VariableSer variables: []*influxdb.Variable{ { ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(7), + OrganizationID: platform.ID(7), Name: "renamed-variable", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -1247,10 +1250,10 @@ func ReplaceVariable(init func(VariableFields, *testing.T) (influxdb.VariableSer // DeleteVariable tests influxdb.VariableService DeleteVariable interface method func DeleteVariable(init func(VariableFields, *testing.T) (influxdb.VariableService, string, func()), t *testing.T) { type args struct { - id influxdb.ID + id platform.ID } type wants struct { - err *influxdb.Error + err *errors.Error variables []*influxdb.Variable } @@ -1266,7 +1269,7 @@ func DeleteVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ Variables: []*influxdb.Variable{ { ID: MustIDBase16(idA), - OrganizationID: influxdb.ID(9), + OrganizationID: platform.ID(9), Name: "m", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -1293,7 +1296,7 @@ func DeleteVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ Variables: []*influxdb.Variable{ { ID: MustIDBase16(idD), - OrganizationID: influxdb.ID(1), + OrganizationID: platform.ID(1), Name: "existing-variable", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -1310,15 +1313,15 @@ func DeleteVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ id: MustIDBase16(idB), }, wants: wants{ - err: &influxdb.Error{ - Code: influxdb.ENotFound, + err: &errors.Error{ + Code: errors.ENotFound, Op: influxdb.OpDeleteVariable, Msg: influxdb.ErrVariableNotFound, }, variables: []*influxdb.Variable{ { ID: MustIDBase16(idD), - OrganizationID: influxdb.ID(1), + OrganizationID: platform.ID(1), Name: "existing-variable", Arguments: &influxdb.VariableArguments{ Type: "constant", @@ -1342,7 +1345,7 @@ func DeleteVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ defer s.ReplaceVariable(ctx, &influxdb.Variable{ ID: tt.args.id, - OrganizationID: influxdb.ID(1), + OrganizationID: platform.ID(1), }) err := s.DeleteVariable(ctx, tt.args.id) @@ -1350,7 +1353,7 @@ func DeleteVariable(init func(VariableFields, *testing.T) (influxdb.VariableServ if tt.wants.err == nil { require.NoError(t, err) } - iErr, ok := err.(*influxdb.Error) + iErr, ok := err.(*errors.Error) require.True(t, ok) assert.Equal(t, iErr.Code, tt.wants.err.Code) assert.Equal(t, strings.HasPrefix(iErr.Error(), tt.wants.err.Error()), true) diff --git a/tests/auth_helpers.go b/tests/auth_helpers.go index 43e058501ef..515c093fb0d 100644 --- a/tests/auth_helpers.go +++ b/tests/auth_helpers.go @@ -2,9 +2,10 @@ package tests import ( "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" ) -func mergePerms(orgID influxdb.ID, in ...[]influxdb.Permission) []influxdb.Permission { +func mergePerms(orgID platform.ID, in ...[]influxdb.Permission) []influxdb.Permission { var perms []influxdb.Permission for i := range in { perms = append(perms, in[i]...) @@ -15,7 +16,7 @@ func mergePerms(orgID influxdb.ID, in ...[]influxdb.Permission) []influxdb.Permi return perms } -func MakeBucketPerm(bucketID influxdb.ID, actions ...influxdb.Action) []influxdb.Permission { +func MakeBucketPerm(bucketID platform.ID, actions ...influxdb.Action) []influxdb.Permission { var perms []influxdb.Permission for i := range actions { perms = append(perms, influxdb.Permission{Action: actions[i], Resource: influxdb.Resource{ID: &bucketID, Type: influxdb.BucketsResourceType}}) @@ -23,11 +24,11 @@ func MakeBucketPerm(bucketID influxdb.ID, actions ...influxdb.Action) []influxdb return perms } -func MakeBucketRWPerm(bucketID influxdb.ID) []influxdb.Permission { +func MakeBucketRWPerm(bucketID platform.ID) []influxdb.Permission { return MakeBucketPerm(bucketID, []influxdb.Action{influxdb.ReadAction, influxdb.WriteAction}...) } -func MakeAuthorization(org, userID influxdb.ID, perms ...[]influxdb.Permission) *influxdb.Authorization { +func MakeAuthorization(org, userID platform.ID, perms ...[]influxdb.Permission) *influxdb.Authorization { return &influxdb.Authorization{ OrgID: org, UserID: userID, diff --git a/tests/client.go b/tests/client.go index a547f532fb8..64690469d5a 100644 --- a/tests/client.go +++ b/tests/client.go @@ -9,6 +9,8 @@ import ( "testing" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/flux/csv" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/authorization" @@ -18,9 +20,9 @@ import ( ) type ClientConfig struct { - UserID influxdb.ID - OrgID influxdb.ID - BucketID influxdb.ID + UserID platform.ID + OrgID platform.ID + BucketID platform.ID DocumentsNamespace string // If Session is provided, Token is ignored. @@ -149,7 +151,7 @@ func QueryRequestBody(flux string) *influxhttp.QueryRequest { // // This authorization token is an operator token for the default // organization for the default user. -func (c *Client) MustCreateAuth(t *testing.T) influxdb.ID { +func (c *Client) MustCreateAuth(t *testing.T) platform.ID { t.Helper() perms := influxdb.OperPermissions() @@ -167,7 +169,7 @@ func (c *Client) MustCreateAuth(t *testing.T) influxdb.ID { // MustCreateBucket creates a bucket or is a fatal error. // Used in tests where the content of the bucket does not matter. -func (c *Client) MustCreateBucket(t *testing.T) influxdb.ID { +func (c *Client) MustCreateBucket(t *testing.T) platform.ID { t.Helper() bucket := &influxdb.Bucket{OrgID: c.OrgID, Name: "n1"} @@ -180,7 +182,7 @@ func (c *Client) MustCreateBucket(t *testing.T) influxdb.ID { // MustCreateOrg creates an org or is a fatal error. // Used in tests where the content of the org does not matter. -func (c *Client) MustCreateOrg(t *testing.T) influxdb.ID { +func (c *Client) MustCreateOrg(t *testing.T) platform.ID { t.Helper() org := &influxdb.Organization{Name: "n1"} @@ -193,7 +195,7 @@ func (c *Client) MustCreateOrg(t *testing.T) influxdb.ID { // MustCreateLabel creates a label or is a fatal error. // Used in tests where the content of the label does not matter. -func (c *Client) MustCreateLabel(t *testing.T) influxdb.ID { +func (c *Client) MustCreateLabel(t *testing.T) platform.ID { t.Helper() l := &influxdb.Label{OrgID: c.OrgID, Name: "n1"} @@ -206,7 +208,7 @@ func (c *Client) MustCreateLabel(t *testing.T) influxdb.ID { // MustCreateCheck creates a check or is a fatal error. // Used in tests where the content of the check does not matter. -func (c *Client) MustCreateCheck(t *testing.T) influxdb.ID { +func (c *Client) MustCreateCheck(t *testing.T) platform.ID { t.Helper() chk, err := c.CreateCheck(context.Background(), MockCheck("c", c.OrgID, c.UserID)) @@ -218,7 +220,7 @@ func (c *Client) MustCreateCheck(t *testing.T) influxdb.ID { // MustCreateTelegraf creates a telegraf config or is a fatal error. // Used in tests where the content of the telegraf config does not matter. -func (c *Client) MustCreateTelegraf(t *testing.T) influxdb.ID { +func (c *Client) MustCreateTelegraf(t *testing.T) platform.ID { t.Helper() tc := &influxdb.TelegrafConfig{ @@ -227,7 +229,7 @@ func (c *Client) MustCreateTelegraf(t *testing.T) influxdb.ID { Description: "d1", Config: "[[howdy]]", } - unused := influxdb.ID(1) /* this id is not used in the API */ + unused := platform.ID(1) /* this id is not used in the API */ err := c.CreateTelegrafConfig(context.Background(), tc, unused) if err != nil { t.Fatalf("unable to create telegraf config: %v", err) @@ -237,7 +239,7 @@ func (c *Client) MustCreateTelegraf(t *testing.T) influxdb.ID { // MustCreateUser creates a user or is a fatal error. // Used in tests where the content of the user does not matter. -func (c *Client) MustCreateUser(t *testing.T) influxdb.ID { +func (c *Client) MustCreateUser(t *testing.T) platform.ID { t.Helper() u := &influxdb.User{Name: "n1"} @@ -250,7 +252,7 @@ func (c *Client) MustCreateUser(t *testing.T) influxdb.ID { // MustCreateVariable creates a variable or is a fatal error. // Used in tests where the content of the variable does not matter. -func (c *Client) MustCreateVariable(t *testing.T) influxdb.ID { +func (c *Client) MustCreateVariable(t *testing.T) platform.ID { t.Helper() v := &influxdb.Variable{ @@ -270,7 +272,7 @@ func (c *Client) MustCreateVariable(t *testing.T) influxdb.ID { // MustCreateNotificationEndpoint creates a notification endpoint or is a fatal error. // Used in tests where the content of the notification endpoint does not matter. -func (c *Client) MustCreateNotificationEndpoint(t *testing.T) influxdb.ID { +func (c *Client) MustCreateNotificationEndpoint(t *testing.T) platform.ID { t.Helper() ne := ValidNotificationEndpoint(c.OrgID) @@ -283,7 +285,7 @@ func (c *Client) MustCreateNotificationEndpoint(t *testing.T) influxdb.ID { // MustCreateNotificationRule creates a Notification Rule or is a fatal error // Used in tests where the content of the notification rule does not matter -func (c *Client) MustCreateNotificationRule(t *testing.T) influxdb.ID { +func (c *Client) MustCreateNotificationRule(t *testing.T) platform.ID { t.Helper() ctx := context.Background() @@ -313,7 +315,7 @@ func (c *Client) MustCreateNotificationRule(t *testing.T) influxdb.ID { // MustCreateDBRPMapping creates a DBRP Mapping or is a fatal error. // Used in tests where the content of the mapping does not matter. // The created mapping points to the user's default bucket. -func (c *Client) MustCreateDBRPMapping(t *testing.T) influxdb.ID { +func (c *Client) MustCreateDBRPMapping(t *testing.T) platform.ID { t.Helper() ctx := context.Background() @@ -341,7 +343,7 @@ func (c *Client) MustCreateDBRPMapping(t *testing.T) influxdb.ID { // // Create a variable: // id := client.MustCreateResource(t, influxdb.VariablesResourceType) // defer client.MustDeleteResource(t, influxdb.VariablesResourceType, id) -func (c *Client) MustCreateResource(t *testing.T, r influxdb.ResourceType) influxdb.ID { +func (c *Client) MustCreateResource(t *testing.T, r influxdb.ResourceType) platform.ID { t.Helper() switch r { @@ -382,7 +384,7 @@ func (c *Client) MustCreateResource(t *testing.T, r influxdb.ResourceType) influ } // DeleteResource will remove a resource using the API. -func (c *Client) DeleteResource(t *testing.T, r influxdb.ResourceType, id influxdb.ID) error { +func (c *Client) DeleteResource(t *testing.T, r influxdb.ResourceType, id platform.ID) error { t.Helper() ctx := context.Background() @@ -426,7 +428,7 @@ func (c *Client) DeleteResource(t *testing.T, r influxdb.ResourceType, id influx } // MustDeleteResource requires no error when deleting a resource. -func (c *Client) MustDeleteResource(t *testing.T, r influxdb.ResourceType, id influxdb.ID) { +func (c *Client) MustDeleteResource(t *testing.T, r influxdb.ResourceType, id platform.ID) { t.Helper() if err := c.DeleteResource(t, r, id); err != nil { @@ -435,10 +437,10 @@ func (c *Client) MustDeleteResource(t *testing.T, r influxdb.ResourceType, id in } // FindAll returns all the IDs of a specific resource type. -func (c *Client) FindAll(t *testing.T, r influxdb.ResourceType) ([]influxdb.ID, error) { +func (c *Client) FindAll(t *testing.T, r influxdb.ResourceType) ([]platform.ID, error) { t.Helper() - var ids []influxdb.ID + var ids []platform.ID ctx := context.Background() switch r { case influxdb.AuthorizationsResourceType: // 0 @@ -546,7 +548,7 @@ func (c *Client) FindAll(t *testing.T, r influxdb.ResourceType) ([]influxdb.ID, // MustFindAll returns all the IDs of a specific resource type; any error // is fatal. -func (c *Client) MustFindAll(t *testing.T, r influxdb.ResourceType) []influxdb.ID { +func (c *Client) MustFindAll(t *testing.T, r influxdb.ResourceType) []platform.ID { t.Helper() ids, err := c.FindAll(t, r) @@ -556,7 +558,7 @@ func (c *Client) MustFindAll(t *testing.T, r influxdb.ResourceType) []influxdb.I return ids } -func (c *Client) AddURM(u influxdb.ID, typ influxdb.UserType, r influxdb.ResourceType, id influxdb.ID) error { +func (c *Client) AddURM(u platform.ID, typ influxdb.UserType, r influxdb.ResourceType, id platform.ID) error { access := &influxdb.UserResourceMapping{ UserID: u, UserType: typ, @@ -572,13 +574,13 @@ func (c *Client) AddURM(u influxdb.ID, typ influxdb.UserType, r influxdb.Resourc } // AddOwner associates the user as owner of the resource. -func (c *Client) AddOwner(user influxdb.ID, r influxdb.ResourceType, id influxdb.ID) error { +func (c *Client) AddOwner(user platform.ID, r influxdb.ResourceType, id platform.ID) error { return c.AddURM(user, influxdb.Owner, r, id) } // MustAddOwner requires that the user is associated with the resource // or the test will be stopped fatally. -func (c *Client) MustAddOwner(t *testing.T, user influxdb.ID, r influxdb.ResourceType, id influxdb.ID) { +func (c *Client) MustAddOwner(t *testing.T, user platform.ID, r influxdb.ResourceType, id platform.ID) { t.Helper() if err := c.AddOwner(user, r, id); err != nil { @@ -587,13 +589,13 @@ func (c *Client) MustAddOwner(t *testing.T, user influxdb.ID, r influxdb.Resourc } // AddMember associates the user as member of the resource. -func (c *Client) AddMember(user influxdb.ID, r influxdb.ResourceType, id influxdb.ID) error { +func (c *Client) AddMember(user platform.ID, r influxdb.ResourceType, id platform.ID) error { return c.AddURM(user, influxdb.Member, r, id) } // MustAddMember requires that the user is associated with the resource // or the test will be stopped fatally. -func (c *Client) MustAddMember(t *testing.T, user influxdb.ID, r influxdb.ResourceType, id influxdb.ID) { +func (c *Client) MustAddMember(t *testing.T, user platform.ID, r influxdb.ResourceType, id platform.ID) { t.Helper() if err := c.AddMember(user, r, id); err != nil { @@ -607,18 +609,18 @@ func (c *Client) MustAddMember(t *testing.T, user influxdb.ID, r influxdb.Resour // from that user to that resource. // Or, put in another way, there can only be one resource mapping from a user to a // resource at a time: either you are a member, or an owner (in that case you are a member too). -func (c *Client) RemoveURM(user, id influxdb.ID) error { +func (c *Client) RemoveURM(user, id platform.ID) error { return c.DeleteUserResourceMapping(context.Background(), id, user) } // RemoveSpecificURM gets around a client issue where deletes doesn't have enough context to remove a urm from // a specific resource type -func (c *Client) RemoveSpecificURM(rt influxdb.ResourceType, ut influxdb.UserType, user, id influxdb.ID) error { +func (c *Client) RemoveSpecificURM(rt influxdb.ResourceType, ut influxdb.UserType, user, id platform.ID) error { return c.SpecificURMSvc(rt, ut).DeleteUserResourceMapping(context.Background(), id, user) } // MustRemoveURM requires that the user is removed as owner/member from the resource. -func (c *Client) MustRemoveURM(t *testing.T, user, id influxdb.ID) { +func (c *Client) MustRemoveURM(t *testing.T, user, id platform.ID) { t.Helper() if err := c.RemoveURM(user, id); err != nil { @@ -627,7 +629,7 @@ func (c *Client) MustRemoveURM(t *testing.T, user, id influxdb.ID) { } // CreateLabelMapping creates a label mapping for label `l` to the resource with `id`. -func (c *Client) CreateLabelMapping(l influxdb.ID, r influxdb.ResourceType, id influxdb.ID) error { +func (c *Client) CreateLabelMapping(l platform.ID, r influxdb.ResourceType, id platform.ID) error { mapping := &influxdb.LabelMapping{ LabelID: l, ResourceType: r, @@ -641,7 +643,7 @@ func (c *Client) CreateLabelMapping(l influxdb.ID, r influxdb.ResourceType, id i // MustCreateLabelMapping requires that the label is associated with the resource // or the test will be stopped fatally. -func (c *Client) MustCreateLabelMapping(t *testing.T, l influxdb.ID, r influxdb.ResourceType, id influxdb.ID) { +func (c *Client) MustCreateLabelMapping(t *testing.T, l platform.ID, r influxdb.ResourceType, id platform.ID) { t.Helper() if err := c.CreateLabelMapping(l, r, id); err != nil { @@ -650,7 +652,7 @@ func (c *Client) MustCreateLabelMapping(t *testing.T, l influxdb.ID, r influxdb. } // FindLabelMappings finds the labels for the specified resource. -func (c *Client) FindLabelMappings(r influxdb.ResourceType, id influxdb.ID) ([]influxdb.ID, error) { +func (c *Client) FindLabelMappings(r influxdb.ResourceType, id platform.ID) ([]platform.ID, error) { filter := influxdb.LabelMappingFilter{ ResourceType: r, ResourceID: id, @@ -662,7 +664,7 @@ func (c *Client) FindLabelMappings(r influxdb.ResourceType, id influxdb.ID) ([]i if err != nil { return nil, err } - var ids []influxdb.ID + var ids []platform.ID for _, r := range ls { ids = append(ids, r.ID) } @@ -670,7 +672,7 @@ func (c *Client) FindLabelMappings(r influxdb.ResourceType, id influxdb.ID) ([]i } // MustFindLabelMappings makes the test fail if an error is found. -func (c *Client) MustFindLabelMappings(t *testing.T, r influxdb.ResourceType, id influxdb.ID) []influxdb.ID { +func (c *Client) MustFindLabelMappings(t *testing.T, r influxdb.ResourceType, id platform.ID) []platform.ID { t.Helper() ls, err := c.FindLabelMappings(r, id) @@ -681,7 +683,7 @@ func (c *Client) MustFindLabelMappings(t *testing.T, r influxdb.ResourceType, id } // DeleteLabelMapping deletes the label for the specified resource. -func (c *Client) DeleteLabelMapping(l influxdb.ID, r influxdb.ResourceType, id influxdb.ID) error { +func (c *Client) DeleteLabelMapping(l platform.ID, r influxdb.ResourceType, id platform.ID) error { m := &influxdb.LabelMapping{ ResourceType: r, ResourceID: id, @@ -694,7 +696,7 @@ func (c *Client) DeleteLabelMapping(l influxdb.ID, r influxdb.ResourceType, id i } // MustDeleteLabelMapping makes the test fail if an error is found. -func (c *Client) MustDeleteLabelMapping(t *testing.T, l influxdb.ID, r influxdb.ResourceType, id influxdb.ID) { +func (c *Client) MustDeleteLabelMapping(t *testing.T, l platform.ID, r influxdb.ResourceType, id platform.ID) { t.Helper() if err := c.DeleteLabelMapping(l, r, id); err != nil { diff --git a/tests/mock.go b/tests/mock.go index 3579a25d01d..450abe7e2dc 100644 --- a/tests/mock.go +++ b/tests/mock.go @@ -4,6 +4,8 @@ import ( "net/http" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" influxhttp "github.com/influxdata/influxdb/v2/http" "github.com/influxdata/influxdb/v2/notification" @@ -13,7 +15,7 @@ import ( ) // ValidCustomNotificationEndpoint creates a NotificationEndpoint with a custom name -func ValidCustomNotificationEndpoint(org influxdb.ID, name string) influxdb.NotificationEndpoint { +func ValidCustomNotificationEndpoint(org platform.ID, name string) influxdb.NotificationEndpoint { return &endpoint.HTTP{ Base: endpoint.Base{ Name: name, @@ -29,12 +31,12 @@ func ValidCustomNotificationEndpoint(org influxdb.ID, name string) influxdb.Noti // ValidNotificationEndpoint returns a valid notification endpoint. // This is the easiest way of "mocking" a influxdb.NotificationEndpoint. -func ValidNotificationEndpoint(org influxdb.ID) influxdb.NotificationEndpoint { +func ValidNotificationEndpoint(org platform.ID) influxdb.NotificationEndpoint { return ValidCustomNotificationEndpoint(org, "howdy") } // ValidNotificationRule returns a valid Notification Rule of type HTTP for testing -func ValidNotificationRule(org, endpoint influxdb.ID) influxdb.NotificationRule { +func ValidNotificationRule(org, endpoint platform.ID) influxdb.NotificationRule { d, _ := notification.FromTimeDuration(time.Second * 5) return &rule.HTTP{ Base: rule.Base{ @@ -54,7 +56,7 @@ func ValidNotificationRule(org, endpoint influxdb.ID) influxdb.NotificationRule } // MockCheck returns a valid check to be used in tests. -func MockCheck(name string, orgID, userID influxdb.ID) *influxhttp.Check { +func MockCheck(name string, orgID, userID platform.ID) *influxhttp.Check { return &influxhttp.Check{ ID: userID, OwnerID: userID, diff --git a/tests/pipeline/fixture.go b/tests/pipeline/fixture.go index 7f307dfd586..bdcf3f5b7e9 100644 --- a/tests/pipeline/fixture.go +++ b/tests/pipeline/fixture.go @@ -4,6 +4,8 @@ import ( "fmt" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/tests" ) @@ -29,7 +31,7 @@ type BaseFixture struct { // NewBaseFixture creates a BaseFixture with and admin, an org owner, a member, and an outsider // for the given orgID and bucketID. -func NewBaseFixture(t *testing.T, p *tests.Pipeline, orgID, bucketID influxdb.ID) BaseFixture { +func NewBaseFixture(t *testing.T, p *tests.Pipeline, orgID, bucketID platform.ID) BaseFixture { fx := BaseFixture{} admin := p.MustNewAdminClient() fx.Admin = admin diff --git a/tests/pipeline_helpers.go b/tests/pipeline_helpers.go index 29d9b1c7470..2d19a0b455c 100644 --- a/tests/pipeline_helpers.go +++ b/tests/pipeline_helpers.go @@ -4,6 +4,8 @@ import ( "context" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/cmd/influxd/launcher" "go.uber.org/zap" @@ -15,9 +17,9 @@ import ( type Pipeline struct { Launcher *launcher.TestLauncher - DefaultOrgID influxdb.ID - DefaultBucketID influxdb.ID - DefaultUserID influxdb.ID + DefaultOrgID platform.ID + DefaultBucketID platform.ID + DefaultUserID platform.ID } // NewDefaultPipeline creates a Pipeline with default @@ -102,7 +104,7 @@ func (p *Pipeline) MustNewAdminClient() *Client { } // MustNewClient returns a client that will direct requests to Launcher. -func (p *Pipeline) MustNewClient(org, bucket influxdb.ID, token string) *Client { +func (p *Pipeline) MustNewClient(org, bucket platform.ID, token string) *Client { config := ClientConfig{ UserID: p.DefaultUserID, OrgID: org, @@ -118,7 +120,7 @@ func (p *Pipeline) MustNewClient(org, bucket influxdb.ID, token string) *Client } // NewBrowserClient returns a client with a cookie session that will direct requests to Launcher. -func (p *Pipeline) NewBrowserClient(org, bucket influxdb.ID, session *influxdb.Session) (*Client, error) { +func (p *Pipeline) NewBrowserClient(org, bucket platform.ID, session *influxdb.Session) (*Client, error) { config := ClientConfig{ UserID: p.DefaultUserID, OrgID: org, @@ -133,7 +135,7 @@ func (p *Pipeline) NewBrowserClient(org, bucket influxdb.ID, session *influxdb.S // The generated browser points to the given org and bucket. // // The user and session are inserted directly into the backing store. -func (p *Pipeline) BrowserFor(org, bucket influxdb.ID, username string) (*Client, influxdb.ID, error) { +func (p *Pipeline) BrowserFor(org, bucket platform.ID, username string) (*Client, platform.ID, error) { ctx := context.Background() user := &influxdb.User{ Name: username, diff --git a/tsdb/store.go b/tsdb/store.go index 1538867a534..149639ba369 100644 --- a/tsdb/store.go +++ b/tsdb/store.go @@ -17,6 +17,8 @@ import ( "sync" "time" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/influxql/query" "github.com/influxdata/influxdb/v2/logger" @@ -1126,8 +1128,8 @@ func (s *Store) MeasurementsSketches(database string) (estimator.Sketch, estimat func (s *Store) BackupShard(id uint64, since time.Time, w io.Writer) error { shard := s.Shard(id) if shard == nil { - return &influxdb.Error{ - Code: influxdb.ENotFound, + return &errors2.Error{ + Code: errors2.ENotFound, Msg: fmt.Sprintf("shard %d not found", id), } } @@ -1143,8 +1145,8 @@ func (s *Store) BackupShard(id uint64, since time.Time, w io.Writer) error { func (s *Store) ExportShard(id uint64, start time.Time, end time.Time, w io.Writer) error { shard := s.Shard(id) if shard == nil { - return &influxdb.Error{ - Code: influxdb.ENotFound, + return &errors2.Error{ + Code: errors2.ENotFound, Msg: fmt.Sprintf("shard %d not found", id), } } diff --git a/usage.go b/usage.go index 2db187e00a9..1bbe27dfa59 100644 --- a/usage.go +++ b/usage.go @@ -3,6 +3,8 @@ package influxdb import ( "context" "time" + + "github.com/influxdata/influxdb/v2/kit/platform" ) // UsageMetric used to track classes of usage. @@ -27,10 +29,10 @@ const ( // Usage is a metric associated with the utilization of a particular resource. type Usage struct { - OrganizationID *ID `json:"organizationID,omitempty"` - BucketID *ID `json:"bucketID,omitempty"` - Type UsageMetric `json:"type"` - Value float64 `json:"value"` + OrganizationID *platform.ID `json:"organizationID,omitempty"` + BucketID *platform.ID `json:"bucketID,omitempty"` + Type UsageMetric `json:"type"` + Value float64 `json:"value"` } // UsageService is a service for accessing usage statistics. @@ -40,8 +42,8 @@ type UsageService interface { // UsageFilter is used to filter usage. type UsageFilter struct { - OrgID *ID - BucketID *ID + OrgID *platform.ID + BucketID *platform.ID Range *Timespan } diff --git a/user.go b/user.go index 3e0f5a4323e..7c685b50ca5 100644 --- a/user.go +++ b/user.go @@ -2,6 +2,9 @@ package influxdb import ( "context" + + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) // UserStatus indicates whether a user is active or inactive @@ -10,7 +13,7 @@ type UserStatus string // Valid validates user status func (u *UserStatus) Valid() error { if *u != "active" && *u != "inactive" { - return &Error{Code: EInvalid, Msg: "Invalid user status"} + return &errors.Error{Code: errors.EInvalid, Msg: "Invalid user status"} } return nil @@ -18,10 +21,10 @@ func (u *UserStatus) Valid() error { // User is a user. 🎉 type User struct { - ID ID `json:"id,omitempty"` - Name string `json:"name"` - OAuthID string `json:"oauthID,omitempty"` - Status Status `json:"status"` + ID platform.ID `json:"id,omitempty"` + Name string `json:"name"` + OAuthID string `json:"oauthID,omitempty"` + Status Status `json:"status"` } // Valid validates user @@ -43,7 +46,7 @@ const ( type UserService interface { // Returns a single user by ID. - FindUserByID(ctx context.Context, id ID) (*User, error) + FindUserByID(ctx context.Context, id platform.ID) (*User, error) // Returns the first user that matches filter. FindUser(ctx context.Context, filter UserFilter) (*User, error) @@ -57,13 +60,13 @@ type UserService interface { // Updates a single user with changeset. // Returns the new user state after update. - UpdateUser(ctx context.Context, id ID, upd UserUpdate) (*User, error) + UpdateUser(ctx context.Context, id platform.ID, upd UserUpdate) (*User, error) // Removes a user by ID. - DeleteUser(ctx context.Context, id ID) error + DeleteUser(ctx context.Context, id platform.ID) error // FindPermissionForUser - FindPermissionForUser(ctx context.Context, UserID ID) (PermissionSet, error) + FindPermissionForUser(ctx context.Context, UserID platform.ID) (PermissionSet, error) } // UserUpdate represents updates to a user. @@ -84,6 +87,6 @@ func (uu UserUpdate) Valid() error { // UserFilter represents a set of filter that restrict the returned results. type UserFilter struct { - ID *ID + ID *platform.ID Name *string } diff --git a/user_resource_mapping.go b/user_resource_mapping.go index 795c15b4486..2e7ccdb2944 100644 --- a/user_resource_mapping.go +++ b/user_resource_mapping.go @@ -4,6 +4,8 @@ import ( "context" "encoding/json" "errors" + + "github.com/influxdata/influxdb/v2/kit/platform" ) var ( @@ -97,16 +99,16 @@ type UserResourceMappingService interface { CreateUserResourceMapping(ctx context.Context, m *UserResourceMapping) error // DeleteUserResourceMapping deletes a user resource mapping. - DeleteUserResourceMapping(ctx context.Context, resourceID, userID ID) error + DeleteUserResourceMapping(ctx context.Context, resourceID, userID platform.ID) error } // UserResourceMapping represents a mapping of a resource to its user. type UserResourceMapping struct { - UserID ID `json:"userID"` + UserID platform.ID `json:"userID"` UserType UserType `json:"userType"` MappingType MappingType `json:"mappingType"` ResourceType ResourceType `json:"resourceType"` - ResourceID ID `json:"resourceID"` + ResourceID platform.ID `json:"resourceID"` } // Validate reports any validation errors for the mapping. @@ -136,9 +138,9 @@ func (m UserResourceMapping) Validate() error { // UserResourceMappingFilter represents a set of filters that restrict the returned results. type UserResourceMappingFilter struct { - ResourceID ID + ResourceID platform.ID ResourceType ResourceType - UserID ID + UserID platform.ID UserType UserType } diff --git a/user_resource_mapping_test.go b/user_resource_mapping_test.go index 049dbaa2125..7ef6218f312 100644 --- a/user_resource_mapping_test.go +++ b/user_resource_mapping_test.go @@ -1,6 +1,7 @@ package influxdb_test import ( + "github.com/influxdata/influxdb/v2/kit/platform" "testing" "github.com/influxdata/influxdb/v2" @@ -10,9 +11,9 @@ import ( func TestOwnerMappingValidate(t *testing.T) { type fields struct { - ResourceID influxdb.ID + ResourceID platform.ID ResourceType influxdb.ResourceType - UserID influxdb.ID + UserID platform.ID UserType influxdb.UserType } tests := []struct { @@ -107,7 +108,7 @@ func TestOwnerMappingToPermissions(t *testing.T) { err bool } - ResourceID, _ := influxdb.IDFromString("020f755c3c082000") + ResourceID, _ := platform.IDFromString("020f755c3c082000") tests := []struct { name string diff --git a/v1/authorization/authorizer.go b/v1/authorization/authorizer.go index 317ed2e0489..058771f0431 100644 --- a/v1/authorization/authorizer.go +++ b/v1/authorization/authorizer.go @@ -4,23 +4,26 @@ import ( "context" "errors" + "github.com/influxdata/influxdb/v2/kit/platform" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" ) var ( - ErrUnsupportedScheme = &influxdb.Error{ - Code: influxdb.EInternal, + ErrUnsupportedScheme = &errors2.Error{ + Code: errors2.EInternal, Msg: "unsupported authorization scheme", } ) type UserFinder interface { // Returns a single user by ID. - FindUserByID(ctx context.Context, id influxdb.ID) (*influxdb.User, error) + FindUserByID(ctx context.Context, id platform.ID) (*influxdb.User, error) } type PasswordComparer interface { - ComparePassword(ctx context.Context, authID influxdb.ID, password string) error + ComparePassword(ctx context.Context, authID platform.ID, password string) error } type AuthTokenFinder interface { @@ -112,10 +115,10 @@ func (v *Authorizer) normalizeError(err error) error { return nil } - var erri *influxdb.Error + var erri *errors2.Error if errors.As(err, &erri) { switch erri.Code { - case influxdb.ENotFound, influxdb.EForbidden: + case errors2.ENotFound, errors2.EForbidden: return influxdb.ErrCredentialsUnauthorized } } diff --git a/v1/authorization/caching_password_service.go b/v1/authorization/caching_password_service.go index f63f02e1b1f..f825c7fda35 100644 --- a/v1/authorization/caching_password_service.go +++ b/v1/authorization/caching_password_service.go @@ -8,6 +8,8 @@ import ( "io" "sync" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) @@ -20,16 +22,16 @@ type CachingPasswordsService struct { inner influxdb.PasswordsService mu sync.RWMutex // protects concurrent access to authCache - authCache map[influxdb.ID]authUser + authCache map[platform.ID]authUser } func NewCachingPasswordsService(inner influxdb.PasswordsService) *CachingPasswordsService { - return &CachingPasswordsService{inner: inner, authCache: make(map[influxdb.ID]authUser)} + return &CachingPasswordsService{inner: inner, authCache: make(map[platform.ID]authUser)} } var _ influxdb.PasswordsService = (*CachingPasswordsService)(nil) -func (c *CachingPasswordsService) SetPassword(ctx context.Context, id influxdb.ID, password string) error { +func (c *CachingPasswordsService) SetPassword(ctx context.Context, id platform.ID, password string) error { err := c.inner.SetPassword(ctx, id, password) if err == nil { c.mu.Lock() @@ -41,7 +43,7 @@ func (c *CachingPasswordsService) SetPassword(ctx context.Context, id influxdb.I // ComparePassword will attempt to perform the comparison using a lower cost hashing function // if influxdb.ContextHasPasswordCacheOption returns true for ctx. -func (c *CachingPasswordsService) ComparePassword(ctx context.Context, id influxdb.ID, password string) error { +func (c *CachingPasswordsService) ComparePassword(ctx context.Context, id platform.ID, password string) error { c.mu.RLock() au, ok := c.authCache[id] c.mu.RUnlock() @@ -68,7 +70,7 @@ func (c *CachingPasswordsService) ComparePassword(ctx context.Context, id influx return nil } -func (c *CachingPasswordsService) CompareAndSetPassword(ctx context.Context, id influxdb.ID, old, new string) error { +func (c *CachingPasswordsService) CompareAndSetPassword(ctx context.Context, id platform.ID, old, new string) error { err := c.inner.CompareAndSetPassword(ctx, id, old, new) if err == nil { c.mu.Lock() diff --git a/v1/authorization/caching_password_service_test.go b/v1/authorization/caching_password_service_test.go index 74b4d04a3f0..acd6ccb9394 100644 --- a/v1/authorization/caching_password_service_test.go +++ b/v1/authorization/caching_password_service_test.go @@ -5,8 +5,9 @@ import ( "strings" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/golang/mock/gomock" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" "github.com/influxdata/influxdb/v2/tenant" "github.com/stretchr/testify/assert" @@ -14,8 +15,8 @@ import ( func TestCachingPasswordsService(t *testing.T) { const ( - user1 = influxdb.ID(1) - user2 = influxdb.ID(2) + user1 = platform.ID(1) + user2 = platform.ID(2) ) makeUser := func(salt, pass string) authUser { diff --git a/v1/authorization/error.go b/v1/authorization/error.go index 2a538375faf..8247169e03b 100644 --- a/v1/authorization/error.go +++ b/v1/authorization/error.go @@ -3,64 +3,64 @@ package authorization import ( "fmt" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform/errors" ) var ( // ErrInvalidAuthID is used when the Authorization's ID cannot be encoded - ErrInvalidAuthID = &influxdb.Error{ - Code: influxdb.EInvalid, + ErrInvalidAuthID = &errors.Error{ + Code: errors.EInvalid, Msg: "authorization ID is invalid", } // ErrAuthNotFound is used when the specified auth cannot be found - ErrAuthNotFound = &influxdb.Error{ - Code: influxdb.ENotFound, + ErrAuthNotFound = &errors.Error{ + Code: errors.ENotFound, Msg: "authorization not found", } // NotUniqueIDError occurs when attempting to create an Authorization with an ID that already belongs to another one - NotUniqueIDError = &influxdb.Error{ - Code: influxdb.EConflict, + NotUniqueIDError = &errors.Error{ + Code: errors.EConflict, Msg: "ID already exists", } // ErrFailureGeneratingID occurs ony when the random number generator // cannot generate an ID in MaxIDGenerationN times. - ErrFailureGeneratingID = &influxdb.Error{ - Code: influxdb.EInternal, + ErrFailureGeneratingID = &errors.Error{ + Code: errors.EInternal, Msg: "unable to generate valid id", } // ErrTokenAlreadyExistsError is used when attempting to create an authorization // with a token that already exists - ErrTokenAlreadyExistsError = &influxdb.Error{ - Code: influxdb.EConflict, + ErrTokenAlreadyExistsError = &errors.Error{ + Code: errors.EConflict, Msg: "token already exists", } ) // ErrInvalidAuthIDError is used when a service was provided an invalid ID. -func ErrInvalidAuthIDError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInvalid, +func ErrInvalidAuthIDError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInvalid, Msg: "auth id provided is invalid", Err: err, } } // ErrInternalServiceError is used when the error comes from an internal system. -func ErrInternalServiceError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func ErrInternalServiceError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Err: err, } } // UnexpectedAuthIndexError is used when the error comes from an internal system. -func UnexpectedAuthIndexError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func UnexpectedAuthIndexError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: fmt.Sprintf("unexpected error retrieving auth index; Err: %v", err), } } diff --git a/v1/authorization/http_client.go b/v1/authorization/http_client.go index 6f62af9705e..62a6a6d9d9a 100644 --- a/v1/authorization/http_client.go +++ b/v1/authorization/http_client.go @@ -4,6 +4,8 @@ import ( "context" "errors" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/pkg/httpc" ) @@ -78,7 +80,7 @@ func (s *Client) FindAuthorizationByToken(ctx context.Context, token string) (*i } // FindAuthorizationByID finds a single Authorization by its ID against a remote influx server. -func (s *Client) FindAuthorizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) { +func (s *Client) FindAuthorizationByID(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) { var b influxdb.Authorization err := s.Client. Get(prefixAuthorization, id.String()). @@ -91,7 +93,7 @@ func (s *Client) FindAuthorizationByID(ctx context.Context, id influxdb.ID) (*in } // UpdateAuthorization updates the status and description if available. -func (s *Client) UpdateAuthorization(ctx context.Context, id influxdb.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { +func (s *Client) UpdateAuthorization(ctx context.Context, id platform.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { var res authResponse err := s.Client. PatchJSON(upd, prefixAuthorization, id.String()). @@ -105,14 +107,14 @@ func (s *Client) UpdateAuthorization(ctx context.Context, id influxdb.ID, upd *i } // DeleteAuthorization removes a authorization by id. -func (s *Client) DeleteAuthorization(ctx context.Context, id influxdb.ID) error { +func (s *Client) DeleteAuthorization(ctx context.Context, id platform.ID) error { return s.Client. Delete(prefixAuthorization, id.String()). Do(ctx) } // SetPassword sets the password for the authorization token id. -func (s *Client) SetPassword(ctx context.Context, id influxdb.ID, password string) error { +func (s *Client) SetPassword(ctx context.Context, id platform.ID, password string) error { return s.Client. PostJSON(passwordSetRequest{ Password: password, diff --git a/v1/authorization/http_server.go b/v1/authorization/http_server.go index fcf61a042ca..19914e9e4bc 100644 --- a/v1/authorization/http_server.go +++ b/v1/authorization/http_server.go @@ -7,6 +7,9 @@ import ( "net/http" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/influxdata/influxdb/v2" @@ -17,15 +20,15 @@ import ( // TenantService is used to look up the Organization and User for an Authorization type TenantService interface { - FindOrganizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) + FindOrganizationByID(ctx context.Context, id platform.ID) (*influxdb.Organization, error) FindOrganization(ctx context.Context, filter influxdb.OrganizationFilter) (*influxdb.Organization, error) - FindUserByID(ctx context.Context, id influxdb.ID) (*influxdb.User, error) + FindUserByID(ctx context.Context, id platform.ID) (*influxdb.User, error) FindUser(ctx context.Context, filter influxdb.UserFilter) (*influxdb.User, error) - FindBucketByID(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) + FindBucketByID(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) } type PasswordService interface { - SetPassword(ctx context.Context, id influxdb.ID, password string) error + SetPassword(ctx context.Context, id platform.ID, password string) error } type AuthHandler struct { @@ -134,20 +137,20 @@ func getAuthorizedUser(r *http.Request, ts TenantService) (*influxdb.User, error type postAuthorizationRequest struct { Token string `json:"token"` Status influxdb.Status `json:"status"` - OrgID influxdb.ID `json:"orgID"` - UserID *influxdb.ID `json:"userID,omitempty"` + OrgID platform.ID `json:"orgID"` + UserID *platform.ID `json:"userID,omitempty"` Description string `json:"description"` Permissions []influxdb.Permission `json:"permissions"` } type authResponse struct { - ID influxdb.ID `json:"id"` + ID platform.ID `json:"id"` Token string `json:"token"` Status influxdb.Status `json:"status"` Description string `json:"description"` - OrgID influxdb.ID `json:"orgID"` + OrgID platform.ID `json:"orgID"` Org string `json:"org"` - UserID influxdb.ID `json:"userID"` + UserID platform.ID `json:"userID"` User string `json:"user"` Permissions []permissionResponse `json:"permissions"` Links map[string]string `json:"links"` @@ -190,7 +193,7 @@ func (h *AuthHandler) newAuthResponse(ctx context.Context, a *influxdb.Authoriza return res, nil } -func (p *postAuthorizationRequest) toInfluxdb(userID influxdb.ID) *influxdb.Authorization { +func (p *postAuthorizationRequest) toInfluxdb(userID platform.ID) *influxdb.Authorization { t := &influxdb.Authorization{ OrgID: p.OrgID, Token: p.Token, @@ -263,24 +266,24 @@ func (p *postAuthorizationRequest) SetDefaults() { func (p *postAuthorizationRequest) Validate() error { if len(p.Permissions) == 0 { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "authorization must include permissions", } } for _, perm := range p.Permissions { if err := perm.Valid(); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } } if !p.OrgID.Valid() { - return &influxdb.Error{ - Err: influxdb.ErrInvalidID, - Code: influxdb.EInvalid, + return &errors.Error{ + Err: platform.ErrInvalidID, + Code: errors.EInvalid, Msg: "org id required", } } @@ -294,9 +297,9 @@ func (p *postAuthorizationRequest) Validate() error { } if p.Token == "" { - return &influxdb.Error{ + return &errors.Error{ Msg: "token required for v1 user authorization type", - Code: influxdb.EInvalid, + Code: errors.EInvalid, } } @@ -326,7 +329,7 @@ func (h *AuthHandler) newPermissionsResponse(ctx context.Context, ps []influxdb. if p.Resource.ID != nil { name, err := h.getNameForResource(ctx, p.Resource.Type, *p.Resource.ID) - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors.ErrorCode(err) == errors.ENotFound { continue } if err != nil { @@ -337,7 +340,7 @@ func (h *AuthHandler) newPermissionsResponse(ctx context.Context, ps []influxdb. if p.Resource.OrgID != nil { name, err := h.getNameForResource(ctx, influxdb.OrgsResourceType, *p.Resource.OrgID) - if influxdb.ErrorCode(err) == influxdb.ENotFound { + if errors.ErrorCode(err) == errors.ENotFound { continue } if err != nil { @@ -349,13 +352,13 @@ func (h *AuthHandler) newPermissionsResponse(ctx context.Context, ps []influxdb. return res, nil } -func (h *AuthHandler) getNameForResource(ctx context.Context, resource influxdb.ResourceType, id influxdb.ID) (string, error) { +func (h *AuthHandler) getNameForResource(ctx context.Context, resource influxdb.ResourceType, id platform.ID) (string, error) { if err := resource.Valid(); err != nil { return "", err } if ok := id.Valid(); !ok { - return "", influxdb.ErrInvalidID + return "", platform.ErrInvalidID } switch resource { @@ -385,8 +388,8 @@ func (h *AuthHandler) getNameForResource(ctx context.Context, resource influxdb. func decodePostAuthorizationRequest(ctx context.Context, r *http.Request) (*postAuthorizationRequest, error) { a := &postAuthorizationRequest{} if err := json.NewDecoder(r.Body).Decode(a); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "invalid json structure", Err: err, } @@ -467,7 +470,7 @@ func decodeGetAuthorizationsRequest(ctx context.Context, r *http.Request) (*getA userID := qp.Get("userID") if userID != "" { - id, err := influxdb.IDFromString(userID) + id, err := platform.IDFromString(userID) if err != nil { return nil, err } @@ -481,7 +484,7 @@ func decodeGetAuthorizationsRequest(ctx context.Context, r *http.Request) (*getA orgID := qp.Get("orgID") if orgID != "" { - id, err := influxdb.IDFromString(orgID) + id, err := platform.IDFromString(orgID) if err != nil { return nil, err } @@ -495,7 +498,7 @@ func decodeGetAuthorizationsRequest(ctx context.Context, r *http.Request) (*getA authID := qp.Get("id") if authID != "" { - id, err := influxdb.IDFromString(authID) + id, err := platform.IDFromString(authID) if err != nil { return nil, err } @@ -513,7 +516,7 @@ func decodeGetAuthorizationsRequest(ctx context.Context, r *http.Request) (*getA func (h *AuthHandler) handleGetAuthorization(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - id, err := influxdb.IDFromString(chi.URLParam(r, "id")) + id, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { h.log.Info("Failed to decode request", zap.String("handler", "getAuthorization"), zap.Error(err)) h.api.Err(w, r, err) @@ -583,12 +586,12 @@ func (h *AuthHandler) handleUpdateAuthorization(w http.ResponseWriter, r *http.R } type updateAuthorizationRequest struct { - ID influxdb.ID + ID platform.ID *influxdb.AuthorizationUpdate } func decodeUpdateAuthorizationRequest(ctx context.Context, r *http.Request) (*updateAuthorizationRequest, error) { - id, err := influxdb.IDFromString(chi.URLParam(r, "id")) + id, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { return nil, err } @@ -606,7 +609,7 @@ func decodeUpdateAuthorizationRequest(ctx context.Context, r *http.Request) (*up // handleDeleteAuthorization is the HTTP handler for the DELETE prefixAuthorization/:id route. func (h *AuthHandler) handleDeleteAuthorization(w http.ResponseWriter, r *http.Request) { - id, err := influxdb.IDFromString(chi.URLParam(r, "id")) + id, err := platform.IDFromString(chi.URLParam(r, "id")) if err != nil { h.log.Info("Failed to decode request", zap.String("handler", "deleteAuthorization"), zap.Error(err)) h.api.Err(w, r, err) @@ -635,17 +638,17 @@ func (h *AuthHandler) handlePostUserPassword(w http.ResponseWriter, r *http.Requ var body passwordSetRequest err := json.NewDecoder(r.Body).Decode(&body) if err != nil { - h.api.Err(w, r, &influxdb.Error{ - Code: influxdb.EInvalid, + h.api.Err(w, r, &errors.Error{ + Code: errors.EInvalid, Err: err, }) return } param := chi.URLParam(r, "id") - authID, err := influxdb.IDFromString(param) + authID, err := platform.IDFromString(param) if err != nil { - h.api.Err(w, r, &influxdb.Error{ + h.api.Err(w, r, &errors.Error{ Msg: "invalid authorization ID provided in route", }) return diff --git a/v1/authorization/http_server_test.go b/v1/authorization/http_server_test.go index 7443b196d9d..4922e180866 100644 --- a/v1/authorization/http_server_test.go +++ b/v1/authorization/http_server_test.go @@ -11,6 +11,9 @@ import ( "sort" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/go-chi/chi" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" @@ -62,19 +65,19 @@ func TestService_handlePostAuthorization(t *testing.T) { }, }, TenantService: &tenantService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ ID: id, Name: "u1", }, nil }, - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: id, Name: "o1", }, nil }, - FindBucketByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: id, Name: "b1", @@ -302,7 +305,7 @@ func TestService_handleGetAuthorization(t *testing.T) { name: "get a authorization by id", fields: fields{ AuthorizationService: &mock.AuthorizationService{ - FindAuthorizationByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) { + FindAuthorizationByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) { if id == itesting.MustIDBase16("020f755c3c082000") { return &influxdb.Authorization{ ID: itesting.MustIDBase16("020f755c3c082000"), @@ -314,7 +317,7 @@ func TestService_handleGetAuthorization(t *testing.T) { Resource: influxdb.Resource{ Type: influxdb.BucketsResourceType, OrgID: itesting.IDPtr(itesting.MustIDBase16("020f755c3c083000")), - ID: func() *influxdb.ID { + ID: func() *platform.ID { id := itesting.MustIDBase16("020f755c3c084000") return &id }(), @@ -329,19 +332,19 @@ func TestService_handleGetAuthorization(t *testing.T) { }, }, TenantService: &tenantService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ ID: id, Name: "u1", }, nil }, - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: id, Name: "o1", }, nil }, - FindBucketByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { + FindBucketByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { return &influxdb.Bucket{ ID: id, Name: "b1", @@ -392,9 +395,9 @@ func TestService_handleGetAuthorization(t *testing.T) { name: "not found", fields: fields{ AuthorizationService: &mock.AuthorizationService{ - FindAuthorizationByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + FindAuthorizationByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) { + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: "authorization not found", } }, @@ -496,14 +499,14 @@ func TestService_handleGetAuthorizations(t *testing.T) { }, }, &tenantService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ ID: id, Name: id.String(), }, nil }, - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: id, Name: id.String(), @@ -588,16 +591,16 @@ func TestService_handleGetAuthorizations(t *testing.T) { }, }, &tenantService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { if id.String() == "2070616e656d2076" { return &influxdb.User{ ID: id, Name: id.String(), }, nil } - return nil, &influxdb.Error{} + return nil, &errors.Error{} }, - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return &influxdb.Organization{ ID: id, Name: id.String(), @@ -664,20 +667,20 @@ func TestService_handleGetAuthorizations(t *testing.T) { }, }, &tenantService{ - FindUserByIDFn: func(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { + FindUserByIDFn: func(ctx context.Context, id platform.ID) (*influxdb.User, error) { return &influxdb.User{ ID: id, Name: id.String(), }, nil }, - FindOrganizationByIDF: func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { + FindOrganizationByIDF: func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { if id.String() == "3070616e656d2076" { return &influxdb.Organization{ ID: id, Name: id.String(), }, nil } - return nil, &influxdb.Error{} + return nil, &errors.Error{} }, }, }, @@ -816,7 +819,7 @@ func TestService_handleDeleteAuthorization(t *testing.T) { name: "remove a authorization by id", fields: fields{ &mock.AuthorizationService{ - DeleteAuthorizationFn: func(ctx context.Context, id influxdb.ID) error { + DeleteAuthorizationFn: func(ctx context.Context, id platform.ID) error { if id == itesting.MustIDBase16("020f755c3c082000") { return nil } @@ -837,9 +840,9 @@ func TestService_handleDeleteAuthorization(t *testing.T) { name: "authorization not found", fields: fields{ &mock.AuthorizationService{ - DeleteAuthorizationFn: func(ctx context.Context, id influxdb.ID) error { - return &influxdb.Error{ - Code: influxdb.ENotFound, + DeleteAuthorizationFn: func(ctx context.Context, id platform.ID) error { + return &errors.Error{ + Code: errors.ENotFound, Msg: "authorization not found", } }, @@ -934,12 +937,12 @@ func jsonDiffErr(s1, s2 string) (diff string, err error) { return s1, fmt.Errorf("s2 is empty") } - var o1 influxdb.Error + var o1 errors.Error if err = json.Unmarshal([]byte(s1), &o1); err != nil { return } - var o2 influxdb.Error + var o2 errors.Error if err = json.Unmarshal([]byte(s2), &o2); err != nil { return } diff --git a/v1/authorization/middleware_auth_password_service.go b/v1/authorization/middleware_auth_password_service.go index 1fd43d0aafd..961e89d294b 100644 --- a/v1/authorization/middleware_auth_password_service.go +++ b/v1/authorization/middleware_auth_password_service.go @@ -3,12 +3,14 @@ package authorization import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/authorizer" ) type AuthFinder interface { - FindAuthorizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) + FindAuthorizationByID(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) } // AuthedPasswordService is middleware for authorizing requests to the inner PasswordService. @@ -23,7 +25,7 @@ func NewAuthedPasswordService(auth AuthFinder, inner PasswordService) *AuthedPas } // SetPassword overrides the password of a known user. -func (s *AuthedPasswordService) SetPassword(ctx context.Context, authID influxdb.ID, password string) error { +func (s *AuthedPasswordService) SetPassword(ctx context.Context, authID platform.ID, password string) error { auth, err := s.auth.FindAuthorizationByID(ctx, authID) if err != nil { return ErrAuthNotFound diff --git a/v1/authorization/middleware_auth_password_service_test.go b/v1/authorization/middleware_auth_password_service_test.go index 5c9c05d620f..ca187f86e05 100644 --- a/v1/authorization/middleware_auth_password_service_test.go +++ b/v1/authorization/middleware_auth_password_service_test.go @@ -2,6 +2,7 @@ package authorization_test import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform/errors" "testing" "github.com/golang/mock/gomock" @@ -28,7 +29,7 @@ func TestAuthedPasswordService_SetPassword(t *testing.T) { af := mocks.NewMockAuthFinder(ctrl) af.EXPECT(). FindAuthorizationByID(ctx, authID). - Return(nil, &influxdb.Error{}) + Return(nil, &errors.Error{}) ps := authorization.NewAuthedPasswordService(af, nil) err := ps.SetPassword(ctx, authID, "foo") diff --git a/v1/authorization/mock_tenant.go b/v1/authorization/mock_tenant.go index 576d62ecf46..0b047f8e6f8 100644 --- a/v1/authorization/mock_tenant.go +++ b/v1/authorization/mock_tenant.go @@ -3,20 +3,22 @@ package authorization import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" ) // tenantService is a mock implementation of an authorization.tenantService type tenantService struct { - FindUserByIDFn func(context.Context, influxdb.ID) (*influxdb.User, error) + FindUserByIDFn func(context.Context, platform.ID) (*influxdb.User, error) FindUserFn func(context.Context, influxdb.UserFilter) (*influxdb.User, error) - FindOrganizationByIDF func(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) + FindOrganizationByIDF func(ctx context.Context, id platform.ID) (*influxdb.Organization, error) FindOrganizationF func(ctx context.Context, filter influxdb.OrganizationFilter) (*influxdb.Organization, error) - FindBucketByIDFn func(context.Context, influxdb.ID) (*influxdb.Bucket, error) + FindBucketByIDFn func(context.Context, platform.ID) (*influxdb.Bucket, error) } // FindUserByID returns a single User by ID. -func (s *tenantService) FindUserByID(ctx context.Context, id influxdb.ID) (*influxdb.User, error) { +func (s *tenantService) FindUserByID(ctx context.Context, id platform.ID) (*influxdb.User, error) { return s.FindUserByIDFn(ctx, id) } @@ -26,7 +28,7 @@ func (s *tenantService) FindUser(ctx context.Context, filter influxdb.UserFilter } //FindOrganizationByID calls FindOrganizationByIDF. -func (s *tenantService) FindOrganizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Organization, error) { +func (s *tenantService) FindOrganizationByID(ctx context.Context, id platform.ID) (*influxdb.Organization, error) { return s.FindOrganizationByIDF(ctx, id) } @@ -35,6 +37,6 @@ func (s *tenantService) FindOrganization(ctx context.Context, filter influxdb.Or return s.FindOrganizationF(ctx, filter) } -func (s *tenantService) FindBucketByID(ctx context.Context, id influxdb.ID) (*influxdb.Bucket, error) { +func (s *tenantService) FindBucketByID(ctx context.Context, id platform.ID) (*influxdb.Bucket, error) { return s.FindBucketByIDFn(ctx, id) } diff --git a/v1/authorization/mocks/auth_finder.go b/v1/authorization/mocks/auth_finder.go index 0702f13f96f..80733678e3d 100644 --- a/v1/authorization/mocks/auth_finder.go +++ b/v1/authorization/mocks/auth_finder.go @@ -8,6 +8,7 @@ import ( context "context" gomock "github.com/golang/mock/gomock" influxdb "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" reflect "reflect" ) @@ -35,7 +36,7 @@ func (m *MockAuthFinder) EXPECT() *MockAuthFinderMockRecorder { } // FindAuthorizationByID mocks base method -func (m *MockAuthFinder) FindAuthorizationByID(arg0 context.Context, arg1 influxdb.ID) (*influxdb.Authorization, error) { +func (m *MockAuthFinder) FindAuthorizationByID(arg0 context.Context, arg1 platform.ID) (*influxdb.Authorization, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "FindAuthorizationByID", arg0, arg1) ret0, _ := ret[0].(*influxdb.Authorization) diff --git a/v1/authorization/mocks/password_comparer.go b/v1/authorization/mocks/password_comparer.go index 87d014e4d86..74d632472aa 100644 --- a/v1/authorization/mocks/password_comparer.go +++ b/v1/authorization/mocks/password_comparer.go @@ -7,7 +7,7 @@ package mocks import ( context "context" gomock "github.com/golang/mock/gomock" - influxdb "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" reflect "reflect" ) @@ -35,7 +35,7 @@ func (m *MockPasswordComparer) EXPECT() *MockPasswordComparerMockRecorder { } // ComparePassword mocks base method -func (m *MockPasswordComparer) ComparePassword(arg0 context.Context, arg1 influxdb.ID, arg2 string) error { +func (m *MockPasswordComparer) ComparePassword(arg0 context.Context, arg1 platform.ID, arg2 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ComparePassword", arg0, arg1, arg2) ret0, _ := ret[0].(error) diff --git a/v1/authorization/mocks/password_service.go b/v1/authorization/mocks/password_service.go index 4c01baeeaf4..0a5de62112d 100644 --- a/v1/authorization/mocks/password_service.go +++ b/v1/authorization/mocks/password_service.go @@ -7,7 +7,7 @@ package mocks import ( context "context" gomock "github.com/golang/mock/gomock" - influxdb "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" reflect "reflect" ) @@ -35,7 +35,7 @@ func (m *MockPasswordService) EXPECT() *MockPasswordServiceMockRecorder { } // SetPassword mocks base method -func (m *MockPasswordService) SetPassword(arg0 context.Context, arg1 influxdb.ID, arg2 string) error { +func (m *MockPasswordService) SetPassword(arg0 context.Context, arg1 platform.ID, arg2 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetPassword", arg0, arg1, arg2) ret0, _ := ret[0].(error) diff --git a/v1/authorization/mocks/user_finder.go b/v1/authorization/mocks/user_finder.go index a1aec48f6f1..aa6737dbec1 100644 --- a/v1/authorization/mocks/user_finder.go +++ b/v1/authorization/mocks/user_finder.go @@ -8,6 +8,7 @@ import ( context "context" gomock "github.com/golang/mock/gomock" influxdb "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" reflect "reflect" ) @@ -35,7 +36,7 @@ func (m *MockUserFinder) EXPECT() *MockUserFinderMockRecorder { } // FindUserByID mocks base method -func (m *MockUserFinder) FindUserByID(arg0 context.Context, arg1 influxdb.ID) (*influxdb.User, error) { +func (m *MockUserFinder) FindUserByID(arg0 context.Context, arg1 platform.ID) (*influxdb.User, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "FindUserByID", arg0, arg1) ret0, _ := ret[0].(*influxdb.User) diff --git a/v1/authorization/service.go b/v1/authorization/service.go index 71834398a01..86086a2544c 100644 --- a/v1/authorization/service.go +++ b/v1/authorization/service.go @@ -4,6 +4,9 @@ import ( "context" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" ) @@ -27,7 +30,7 @@ func NewService(st *Store, ts TenantService) *Service { func (s *Service) CreateAuthorization(ctx context.Context, a *influxdb.Authorization) error { if err := a.Valid(); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -63,7 +66,7 @@ func (s *Service) CreateAuthorization(ctx context.Context, a *influxdb.Authoriza }) } -func (s *Service) FindAuthorizationByID(ctx context.Context, id influxdb.ID) (*influxdb.Authorization, error) { +func (s *Service) FindAuthorizationByID(ctx context.Context, id platform.ID) (*influxdb.Authorization, error) { var a *influxdb.Authorization err := s.store.View(ctx, func(tx kv.Tx) error { auth, err := s.store.GetAuthorizationByID(ctx, tx, id) @@ -118,7 +121,7 @@ func (s *Service) FindAuthorizations(ctx context.Context, filter influxdb.Author return nil }) if err != nil { - return nil, 0, &influxdb.Error{ + return nil, 0, &errors.Error{ Err: err, } } @@ -137,7 +140,7 @@ func (s *Service) FindAuthorizations(ctx context.Context, filter influxdb.Author return nil }) if err != nil { - return nil, 0, &influxdb.Error{ + return nil, 0, &errors.Error{ Err: err, } } @@ -156,7 +159,7 @@ func (s *Service) FindAuthorizations(ctx context.Context, filter influxdb.Author }) if err != nil { - return nil, 0, &influxdb.Error{ + return nil, 0, &errors.Error{ Err: err, } } @@ -165,7 +168,7 @@ func (s *Service) FindAuthorizations(ctx context.Context, filter influxdb.Author } // UpdateAuthorization updates the status and description if available. -func (s *Service) UpdateAuthorization(ctx context.Context, id influxdb.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { +func (s *Service) UpdateAuthorization(ctx context.Context, id platform.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) { var auth *influxdb.Authorization err := s.store.View(ctx, func(tx kv.Tx) error { a, e := s.store.GetAuthorizationByID(ctx, tx, id) @@ -177,8 +180,8 @@ func (s *Service) UpdateAuthorization(ctx context.Context, id influxdb.ID, upd * }) if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Err: err, } } @@ -203,7 +206,7 @@ func (s *Service) UpdateAuthorization(ctx context.Context, id influxdb.ID, upd * return auth, err } -func (s *Service) DeleteAuthorization(ctx context.Context, id influxdb.ID) error { +func (s *Service) DeleteAuthorization(ctx context.Context, id platform.ID) error { return s.store.Update(ctx, func(tx kv.Tx) (err error) { return s.store.DeleteAuthorization(ctx, tx, id) }) diff --git a/v1/authorization/service_password.go b/v1/authorization/service_password.go index 15b88708ba8..1483aea4703 100644 --- a/v1/authorization/service_password.go +++ b/v1/authorization/service_password.go @@ -3,7 +3,9 @@ package authorization import ( "context" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2/kv" "github.com/influxdata/influxdb/v2/tenant" "golang.org/x/crypto/bcrypt" @@ -15,12 +17,12 @@ var EIncorrectPassword = tenant.EIncorrectPassword // SetPasswordHash returns an error. // // This API is intended for upgrading 1.x users. -func (s *Service) SetPasswordHash(ctx context.Context, authID influxdb.ID, passHash string) error { +func (s *Service) SetPasswordHash(ctx context.Context, authID platform.ID, passHash string) error { // verify passHash is a valid bcrypt hash _, err := bcrypt.Cost([]byte(passHash)) if err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Msg: "invalid bcrypt hash", Err: err, } @@ -36,7 +38,7 @@ func (s *Service) SetPasswordHash(ctx context.Context, authID influxdb.ID, passH } // SetPassword overrides the password of a known user. -func (s *Service) SetPassword(ctx context.Context, authID influxdb.ID, password string) error { +func (s *Service) SetPassword(ctx context.Context, authID platform.ID, password string) error { if len(password) < tenant.MinPasswordLen { return tenant.EShortPassword } @@ -56,7 +58,7 @@ func (s *Service) SetPassword(ctx context.Context, authID influxdb.ID, password // ComparePassword checks if the password matches the password recorded. // Passwords that do not match return errors. -func (s *Service) ComparePassword(ctx context.Context, authID influxdb.ID, password string) error { +func (s *Service) ComparePassword(ctx context.Context, authID platform.ID, password string) error { // get password var hash []byte err := s.store.View(ctx, func(tx kv.Tx) error { @@ -87,7 +89,7 @@ func (s *Service) ComparePassword(ctx context.Context, authID influxdb.ID, passw // CompareAndSetPassword checks the password and if they match // updates to the new password. -func (s *Service) CompareAndSetPassword(ctx context.Context, authID influxdb.ID, old, new string) error { +func (s *Service) CompareAndSetPassword(ctx context.Context, authID platform.ID, old, new string) error { err := s.ComparePassword(ctx, authID, old) if err != nil { return err diff --git a/v1/authorization/storage.go b/v1/authorization/storage.go index 96afc5725f7..738ba3a3855 100644 --- a/v1/authorization/storage.go +++ b/v1/authorization/storage.go @@ -3,7 +3,9 @@ package authorization import ( "context" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2/kit/tracing" "github.com/influxdata/influxdb/v2/kv" "github.com/influxdata/influxdb/v2/snowflake" @@ -19,7 +21,7 @@ var ( type Store struct { kvStore kv.Store - IDGen influxdb.IDGenerator + IDGen platform.IDGenerator } func NewStore(kvStore kv.Store) (*Store, error) { @@ -56,7 +58,7 @@ func (s *Store) setup() error { // generateSafeID attempts to create ids for buckets // and orgs that are without backslash, commas, and spaces, BUT ALSO do not already exist. -func (s *Store) generateSafeID(ctx context.Context, tx kv.Tx, bucket []byte) (influxdb.ID, error) { +func (s *Store) generateSafeID(ctx context.Context, tx kv.Tx, bucket []byte) (platform.ID, error) { for i := 0; i < MaxIDGenerationN; i++ { id := s.IDGen.ID() @@ -75,19 +77,19 @@ func (s *Store) generateSafeID(ctx context.Context, tx kv.Tx, bucket []byte) (in continue } - return influxdb.InvalidID(), err + return platform.InvalidID(), err } - return influxdb.InvalidID(), ErrFailureGeneratingID + return platform.InvalidID(), ErrFailureGeneratingID } -func (s *Store) uniqueID(ctx context.Context, tx kv.Tx, bucket []byte, id influxdb.ID) error { +func (s *Store) uniqueID(ctx context.Context, tx kv.Tx, bucket []byte, id platform.ID) error { span, _ := tracing.StartSpanFromContext(ctx) defer span.Finish() encodedID, err := id.Encode() if err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Err: err, } } diff --git a/v1/authorization/storage_authorization.go b/v1/authorization/storage_authorization.go index 33006f2659a..fe89c7680fc 100644 --- a/v1/authorization/storage_authorization.go +++ b/v1/authorization/storage_authorization.go @@ -4,6 +4,9 @@ import ( "context" "encoding/json" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/buger/jsonparser" "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/kv" @@ -29,8 +32,8 @@ func encodeAuthorization(a *influxdb.Authorization) ([]byte, error) { case "": a.Status = influxdb.Active default: - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Msg: "unknown authorization status", } } @@ -72,8 +75,8 @@ func (s *Store) CreateAuthorization(ctx context.Context, tx kv.Tx, a *influxdb.A v, err := encodeAuthorization(a) if err != nil { - return &influxdb.Error{ - Code: influxdb.EInvalid, + return &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -89,8 +92,8 @@ func (s *Store) CreateAuthorization(ctx context.Context, tx kv.Tx, a *influxdb.A } if err := idx.Put(authIndexKey(a.Token), encodedID); err != nil { - return &influxdb.Error{ - Code: influxdb.EInternal, + return &errors.Error{ + Code: errors.EInternal, Err: err, } } @@ -101,7 +104,7 @@ func (s *Store) CreateAuthorization(ctx context.Context, tx kv.Tx, a *influxdb.A } if err := b.Put(encodedID, v); err != nil { - return &influxdb.Error{ + return &errors.Error{ Err: err, } } @@ -110,7 +113,7 @@ func (s *Store) CreateAuthorization(ctx context.Context, tx kv.Tx, a *influxdb.A } // GetAuthorization gets an authorization by its ID from the auth bucket in kv -func (s *Store) GetAuthorizationByID(ctx context.Context, tx kv.Tx, id influxdb.ID) (*influxdb.Authorization, error) { +func (s *Store) GetAuthorizationByID(ctx context.Context, tx kv.Tx, id platform.ID) (*influxdb.Authorization, error) { encodedID, err := id.Encode() if err != nil { return nil, ErrInvalidAuthID @@ -132,8 +135,8 @@ func (s *Store) GetAuthorizationByID(ctx context.Context, tx kv.Tx, id influxdb. a := &influxdb.Authorization{} if err := decodeAuthorization(v, a); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -150,16 +153,16 @@ func (s *Store) GetAuthorizationByToken(ctx context.Context, tx kv.Tx, token str // use the token to look up the authorization's ID idKey, err := idx.Get(authIndexKey(token)) if kv.IsNotFound(err) { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Msg: "authorization not found", } } - var id influxdb.ID + var id platform.ID if err := id.Decode(idKey); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } @@ -221,19 +224,19 @@ func (s *Store) forEachAuthorization(ctx context.Context, tx kv.Tx, pred kv.Curs } // UpdateAuthorization updates the status and description only of an authorization -func (s *Store) UpdateAuthorization(ctx context.Context, tx kv.Tx, id influxdb.ID, a *influxdb.Authorization) (*influxdb.Authorization, error) { +func (s *Store) UpdateAuthorization(ctx context.Context, tx kv.Tx, id platform.ID, a *influxdb.Authorization) (*influxdb.Authorization, error) { v, err := encodeAuthorization(a) if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInvalid, + return nil, &errors.Error{ + Code: errors.EInvalid, Err: err, } } encodedID, err := a.ID.Encode() if err != nil { - return nil, &influxdb.Error{ - Code: influxdb.ENotFound, + return nil, &errors.Error{ + Code: errors.ENotFound, Err: err, } } @@ -244,8 +247,8 @@ func (s *Store) UpdateAuthorization(ctx context.Context, tx kv.Tx, id influxdb.I } if err := idx.Put(authIndexKey(a.Token), encodedID); err != nil { - return nil, &influxdb.Error{ - Code: influxdb.EInternal, + return nil, &errors.Error{ + Code: errors.EInternal, Err: err, } } @@ -256,7 +259,7 @@ func (s *Store) UpdateAuthorization(ctx context.Context, tx kv.Tx, id influxdb.I } if err := b.Put(encodedID, v); err != nil { - return nil, &influxdb.Error{ + return nil, &errors.Error{ Err: err, } } @@ -266,7 +269,7 @@ func (s *Store) UpdateAuthorization(ctx context.Context, tx kv.Tx, id influxdb.I } // DeleteAuthorization removes an authorization from storage -func (s *Store) DeleteAuthorization(ctx context.Context, tx kv.Tx, id influxdb.ID) error { +func (s *Store) DeleteAuthorization(ctx context.Context, tx kv.Tx, id platform.ID) error { a, err := s.GetAuthorizationByID(ctx, tx, id) if err != nil { return err @@ -332,7 +335,7 @@ func unique(ctx context.Context, tx kv.Tx, indexBucket, indexKey []byte) error { } // uniqueID returns nil if the ID provided is unique, returns an error otherwise -func uniqueID(ctx context.Context, tx kv.Tx, id influxdb.ID) error { +func uniqueID(ctx context.Context, tx kv.Tx, id platform.ID) error { encodedID, err := id.Encode() if err != nil { return ErrInvalidAuthID diff --git a/v1/authorization/storage_authorization_test.go b/v1/authorization/storage_authorization_test.go index 2fdc090e4bd..496ca490158 100644 --- a/v1/authorization/storage_authorization_test.go +++ b/v1/authorization/storage_authorization_test.go @@ -6,6 +6,8 @@ import ( "reflect" "testing" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/inmem" "github.com/influxdata/influxdb/v2/kv" @@ -19,10 +21,10 @@ func TestAuth(t *testing.T) { setup := func(t *testing.T, store *Store, tx kv.Tx) { for i := 1; i <= 10; i++ { err := store.CreateAuthorization(context.Background(), tx, &influxdb.Authorization{ - ID: influxdb.ID(i), + ID: platform.ID(i), Token: fmt.Sprintf("randomtoken%d", i), - OrgID: influxdb.ID(i), - UserID: influxdb.ID(i), + OrgID: platform.ID(i), + UserID: platform.ID(i), Status: influxdb.Active, }) @@ -54,10 +56,10 @@ func TestAuth(t *testing.T) { expected := []*influxdb.Authorization{} for i := 1; i <= 10; i++ { expected = append(expected, &influxdb.Authorization{ - ID: influxdb.ID(i), + ID: platform.ID(i), Token: fmt.Sprintf("randomtoken%d", i), - OrgID: influxdb.ID(i), - UserID: influxdb.ID(i), + OrgID: platform.ID(i), + UserID: platform.ID(i), Status: "active", }) } @@ -67,10 +69,10 @@ func TestAuth(t *testing.T) { // should not be able to create two authorizations with identical tokens err = store.CreateAuthorization(context.Background(), tx, &influxdb.Authorization{ - ID: influxdb.ID(1), + ID: platform.ID(1), Token: fmt.Sprintf("randomtoken%d", 1), - OrgID: influxdb.ID(1), - UserID: influxdb.ID(1), + OrgID: platform.ID(1), + UserID: platform.ID(1), }) if err == nil { t.Fatalf("expected to be unable to create authorizations with identical tokens") @@ -83,14 +85,14 @@ func TestAuth(t *testing.T) { results: func(t *testing.T, store *Store, tx kv.Tx) { for i := 1; i <= 10; i++ { expectedAuth := &influxdb.Authorization{ - ID: influxdb.ID(i), + ID: platform.ID(i), Token: fmt.Sprintf("randomtoken%d", i), - OrgID: influxdb.ID(i), - UserID: influxdb.ID(i), + OrgID: platform.ID(i), + UserID: platform.ID(i), Status: influxdb.Active, } - authByID, err := store.GetAuthorizationByID(context.Background(), tx, influxdb.ID(i)) + authByID, err := store.GetAuthorizationByID(context.Background(), tx, platform.ID(i)) if err != nil { t.Fatalf("Unexpectedly could not acquire Authorization by ID [Error]: %v", err) } @@ -116,14 +118,14 @@ func TestAuth(t *testing.T) { setup: setup, update: func(t *testing.T, store *Store, tx kv.Tx) { for i := 1; i <= 10; i++ { - auth, err := store.GetAuthorizationByID(context.Background(), tx, influxdb.ID(i)) + auth, err := store.GetAuthorizationByID(context.Background(), tx, platform.ID(i)) if err != nil { t.Fatalf("Could not get authorization [Error]: %v", err) } auth.Status = influxdb.Inactive - _, err = store.UpdateAuthorization(context.Background(), tx, influxdb.ID(i), auth) + _, err = store.UpdateAuthorization(context.Background(), tx, platform.ID(i), auth) if err != nil { t.Fatalf("Could not get updated authorization [Error]: %v", err) } @@ -132,16 +134,16 @@ func TestAuth(t *testing.T) { results: func(t *testing.T, store *Store, tx kv.Tx) { for i := 1; i <= 10; i++ { - auth, err := store.GetAuthorizationByID(context.Background(), tx, influxdb.ID(i)) + auth, err := store.GetAuthorizationByID(context.Background(), tx, platform.ID(i)) if err != nil { t.Fatalf("Could not get authorization [Error]: %v", err) } expectedAuth := &influxdb.Authorization{ - ID: influxdb.ID(i), + ID: platform.ID(i), Token: fmt.Sprintf("randomtoken%d", i), - OrgID: influxdb.ID(i), - UserID: influxdb.ID(i), + OrgID: platform.ID(i), + UserID: platform.ID(i), Status: influxdb.Inactive, } @@ -156,7 +158,7 @@ func TestAuth(t *testing.T) { setup: setup, update: func(t *testing.T, store *Store, tx kv.Tx) { for i := 1; i <= 10; i++ { - err := store.DeleteAuthorization(context.Background(), tx, influxdb.ID(i)) + err := store.DeleteAuthorization(context.Background(), tx, platform.ID(i)) if err != nil { t.Fatalf("Could not delete authorization [Error]: %v", err) } @@ -164,7 +166,7 @@ func TestAuth(t *testing.T) { }, results: func(t *testing.T, store *Store, tx kv.Tx) { for i := 1; i <= 10; i++ { - _, err := store.GetAuthorizationByID(context.Background(), tx, influxdb.ID(i)) + _, err := store.GetAuthorizationByID(context.Background(), tx, platform.ID(i)) if err == nil { t.Fatal("Authorization was not deleted correctly") } @@ -226,7 +228,7 @@ func TestAuth(t *testing.T) { func Test_filterAuthorizationsFn(t *testing.T) { var ( - otherID = influxdb.ID(999) + otherID = platform.ID(999) ) auth := influxdb.Authorization{ diff --git a/v1/authorization/storage_password.go b/v1/authorization/storage_password.go index 464c1d76d63..4912c4874b1 100644 --- a/v1/authorization/storage_password.go +++ b/v1/authorization/storage_password.go @@ -3,7 +3,9 @@ package authorization import ( "context" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2/kv" ) @@ -14,15 +16,15 @@ var ( // UnavailablePasswordServiceError is used if we aren't able to add the // password to the store, it means the store is not available at the moment // (e.g. network). -func UnavailablePasswordServiceError(err error) *influxdb.Error { - return &influxdb.Error{ - Code: influxdb.EInternal, +func UnavailablePasswordServiceError(err error) *errors.Error { + return &errors.Error{ + Code: errors.EInternal, Msg: "unable to access password bucket", Err: err, } } -func (s *Store) GetPassword(ctx context.Context, tx kv.Tx, id influxdb.ID) (string, error) { +func (s *Store) GetPassword(ctx context.Context, tx kv.Tx, id platform.ID) (string, error) { encodedID, err := id.Encode() if err != nil { return "", ErrInvalidAuthIDError(err) @@ -38,7 +40,7 @@ func (s *Store) GetPassword(ctx context.Context, tx kv.Tx, id influxdb.ID) (stri return string(passwd), err } -func (s *Store) SetPassword(ctx context.Context, tx kv.Tx, id influxdb.ID, password string) error { +func (s *Store) SetPassword(ctx context.Context, tx kv.Tx, id platform.ID, password string) error { encodedID, err := id.Encode() if err != nil { return ErrInvalidAuthIDError(err) @@ -52,7 +54,7 @@ func (s *Store) SetPassword(ctx context.Context, tx kv.Tx, id influxdb.ID, passw return b.Put(encodedID, []byte(password)) } -func (s *Store) DeletePassword(ctx context.Context, tx kv.Tx, id influxdb.ID) error { +func (s *Store) DeletePassword(ctx context.Context, tx kv.Tx, id platform.ID) error { encodedID, err := id.Encode() if err != nil { return ErrInvalidAuthIDError(err) diff --git a/v1/coordinator/shard_mapper.go b/v1/coordinator/shard_mapper.go index e5f2a30c527..05e3d5ecc0b 100644 --- a/v1/coordinator/shard_mapper.go +++ b/v1/coordinator/shard_mapper.go @@ -6,6 +6,8 @@ import ( "io" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/influxql/query" "github.com/influxdata/influxdb/v2/tsdb" @@ -48,7 +50,7 @@ func (e *LocalShardMapper) MapShards(ctx context.Context, sources influxql.Sourc return a, nil } -func (e *LocalShardMapper) mapShards(ctx context.Context, a *LocalShardMapping, sources influxql.Sources, tmin, tmax time.Time, orgID influxdb.ID) error { +func (e *LocalShardMapper) mapShards(ctx context.Context, a *LocalShardMapping, sources influxql.Sources, tmin, tmax time.Time, orgID platform.ID) error { for _, s := range sources { switch s := s.(type) { case *influxql.Measurement: diff --git a/v1/coordinator/shard_mapper_test.go b/v1/coordinator/shard_mapper_test.go index 1a171849e9a..87eefbd2bc9 100644 --- a/v1/coordinator/shard_mapper_test.go +++ b/v1/coordinator/shard_mapper_test.go @@ -2,6 +2,7 @@ package coordinator_test import ( "context" + "github.com/influxdata/influxdb/v2/kit/platform" "reflect" "testing" "time" @@ -22,8 +23,8 @@ func TestLocalShardMapper(t *testing.T) { defer ctrl.Finish() dbrp := mocks.NewMockDBRPMappingServiceV2(ctrl) - orgID := influxdb.ID(0xff00) - bucketID := influxdb.ID(0xffee) + orgID := platform.ID(0xff00) + bucketID := platform.ID(0xffee) db := "db0" rp := "rp0" filt := influxdb.DBRPMappingFilterV2{OrgID: &orgID, Database: &db, RetentionPolicy: &rp} diff --git a/v1/coordinator/statement_executor.go b/v1/coordinator/statement_executor.go index c48bc416aae..aa2a6dc489a 100644 --- a/v1/coordinator/statement_executor.go +++ b/v1/coordinator/statement_executor.go @@ -7,6 +7,8 @@ import ( "strings" "time" + errors2 "github.com/influxdata/influxdb/v2/kit/platform/errors" + "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/authorizer" iql "github.com/influxdata/influxdb/v2/influxql" @@ -336,7 +338,7 @@ func (e *StatementExecutor) executeShowDatabasesStatement(ctx context.Context, q } err = authorizer.IsAllowed(ctx, *perm) if err != nil { - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors2.ErrorCode(err) == errors2.EUnauthorized { continue } return nil, err @@ -455,7 +457,7 @@ func (e *StatementExecutor) executeShowRetentionPoliciesStatement(ctx context.Co } err = authorizer.IsAllowed(ctx, *perm) if err != nil { - if influxdb.ErrorCode(err) == influxdb.EUnauthorized { + if errors2.ErrorCode(err) == errors2.EUnauthorized { continue } return nil, err diff --git a/v1/coordinator/statement_executor_test.go b/v1/coordinator/statement_executor_test.go index 85c148c4e43..bb10f8e83e6 100644 --- a/v1/coordinator/statement_executor_test.go +++ b/v1/coordinator/statement_executor_test.go @@ -5,6 +5,7 @@ import ( "context" "errors" "fmt" + "github.com/influxdata/influxdb/v2/kit/platform" "reflect" "regexp" "testing" @@ -42,7 +43,7 @@ func TestQueryExecutor_ExecuteQuery_SelectStatement(t *testing.T) { defer ctrl.Finish() dbrp := mocks.NewMockDBRPMappingServiceV2(ctrl) - orgID := influxdb.ID(0xff00) + orgID := platform.ID(0xff00) empty := "" filt := influxdb.DBRPMappingFilterV2{OrgID: &orgID, Database: &empty, RetentionPolicy: &empty} res := []*influxdb.DBRPMappingV2{{}} @@ -108,7 +109,7 @@ func TestQueryExecutor_ExecuteQuery_MaxSelectBucketsN(t *testing.T) { defer ctrl.Finish() dbrp := mocks.NewMockDBRPMappingServiceV2(ctrl) - orgID := influxdb.ID(0xff00) + orgID := platform.ID(0xff00) empty := "" filt := influxdb.DBRPMappingFilterV2{OrgID: &orgID, Database: &empty, RetentionPolicy: &empty} res := []*influxdb.DBRPMappingV2{{}} @@ -226,8 +227,8 @@ func TestStatementExecutor_NormalizeStatement(t *testing.T) { defer ctrl.Finish() dbrp := mocks.NewMockDBRPMappingServiceV2(ctrl) - orgID := influxdb.ID(0xff00) - bucketID := influxdb.ID(0xffee) + orgID := platform.ID(0xff00) + bucketID := platform.ID(0xffee) filt := influxdb.DBRPMappingFilterV2{OrgID: &orgID, Database: &testCase.expectedDB} res := []*influxdb.DBRPMappingV2{{Database: testCase.expectedDB, RetentionPolicy: testCase.expectedRP, OrganizationID: orgID, BucketID: bucketID, Default: true}} dbrp.EXPECT(). @@ -330,7 +331,7 @@ func TestQueryExecutor_ExecuteQuery_ShowDatabases(t *testing.T) { defer ctrl.Finish() dbrp := mocks.NewMockDBRPMappingServiceV2(ctrl) - orgID := influxdb.ID(0xff00) + orgID := platform.ID(0xff00) filt := influxdb.DBRPMappingFilterV2{OrgID: &orgID} res := []*influxdb.DBRPMappingV2{ {Database: "db1", OrganizationID: orgID, BucketID: 0xffe0}, @@ -451,7 +452,7 @@ func DefaultQueryExecutor(t *testing.T, opts ...optFn) *QueryExecutor { } // ExecuteQuery parses query and executes against the database. -func (e *QueryExecutor) ExecuteQuery(ctx context.Context, q, database string, chunkSize int, orgID influxdb.ID) (<-chan *query.Result, *influxql2.Statistics) { +func (e *QueryExecutor) ExecuteQuery(ctx context.Context, q, database string, chunkSize int, orgID platform.ID) (<-chan *query.Result, *influxql2.Statistics) { return e.Executor.ExecuteQuery(ctx, MustParseQuery(q), query.ExecutionOptions{ OrgID: orgID, Database: database, diff --git a/v1/services/storage/source.go b/v1/services/storage/source.go index eb71b6e0c2b..338f0a16c9f 100644 --- a/v1/services/storage/source.go +++ b/v1/services/storage/source.go @@ -2,7 +2,7 @@ package storage import ( "github.com/gogo/protobuf/types" - "github.com/influxdata/influxdb/v2" + "github.com/influxdata/influxdb/v2/kit/platform" ) // this is easier than fooling around with .proto files. @@ -25,10 +25,10 @@ func getReadSource(any types.Any) (readSource, error) { return source, nil } -func (r *readSource) GetOrgID() influxdb.ID { - return influxdb.ID(r.OrganizationID) +func (r *readSource) GetOrgID() platform.ID { + return platform.ID(r.OrganizationID) } -func (r *readSource) GetBucketID() influxdb.ID { - return influxdb.ID(r.BucketID) +func (r *readSource) GetBucketID() platform.ID { + return platform.ID(r.BucketID) } diff --git a/v1/services/storage/store.go b/v1/services/storage/store.go index e8b655883b6..1c03a1412a9 100644 --- a/v1/services/storage/store.go +++ b/v1/services/storage/store.go @@ -7,9 +7,10 @@ import ( "sort" "time" + "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/gogo/protobuf/proto" "github.com/gogo/protobuf/types" - "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/influxql/query" "github.com/influxdata/influxdb/v2/models" "github.com/influxdata/influxdb/v2/pkg/slices" @@ -129,7 +130,7 @@ func (s *Store) findShardIDs(database, rp string, desc bool, start, end int64) ( } func (s *Store) validateArgs(orgID, bucketID uint64, start, end int64) (string, string, int64, int64, error) { - database := influxdb.ID(bucketID).String() + database := platform.ID(bucketID).String() rp := meta.DefaultRetentionPolicyName di := s.MetaClient.Database(database) @@ -234,7 +235,7 @@ func (s *Store) ReadGroup(ctx context.Context, req *datatypes.ReadGroupRequest) } type metaqueryAttributes struct { - orgID influxdb.ID + orgID platform.ID db, rp string start, end int64 pred influxql.Expr diff --git a/variable.go b/variable.go index 68cbc87dffa..16d796781e6 100644 --- a/variable.go +++ b/variable.go @@ -6,6 +6,8 @@ import ( "fmt" "net/url" "regexp" + + "github.com/influxdata/influxdb/v2/kit/platform" ) // ErrVariableNotFound is the error msg for a missing variable. @@ -24,7 +26,7 @@ const ( // VariableService describes a service for managing Variables type VariableService interface { // FindVariableByID finds a single variable from the store by its ID - FindVariableByID(ctx context.Context, id ID) (*Variable, error) + FindVariableByID(ctx context.Context, id platform.ID) (*Variable, error) // FindVariables returns all variables in the store FindVariables(ctx context.Context, filter VariableFilter, opt ...FindOptions) ([]*Variable, error) @@ -33,20 +35,20 @@ type VariableService interface { CreateVariable(ctx context.Context, m *Variable) error // UpdateVariable updates a single variable with a changeset - UpdateVariable(ctx context.Context, id ID, update *VariableUpdate) (*Variable, error) + UpdateVariable(ctx context.Context, id platform.ID, update *VariableUpdate) (*Variable, error) // ReplaceVariable replaces a single variable ReplaceVariable(ctx context.Context, variable *Variable) error // DeleteVariable removes a variable from the store - DeleteVariable(ctx context.Context, id ID) error + DeleteVariable(ctx context.Context, id platform.ID) error } // A Variable describes a keyword that can be expanded into several possible // values when used in an InfluxQL or Flux query type Variable struct { - ID ID `json:"id,omitempty"` - OrganizationID ID `json:"orgID,omitempty"` + ID platform.ID `json:"id,omitempty"` + OrganizationID platform.ID `json:"orgID,omitempty"` Name string `json:"name"` Description string `json:"description"` Selected []string `json:"selected"` @@ -59,8 +61,8 @@ var DefaultVariableFindOptions = FindOptions{} // VariableFilter represents a set of filter that restrict the returned results. type VariableFilter struct { - ID *ID - OrganizationID *ID + ID *platform.ID + OrganizationID *platform.ID Organization *string } diff --git a/vault/secret.go b/vault/secret.go index 6fe6215527b..305aaf2573a 100644 --- a/vault/secret.go +++ b/vault/secret.go @@ -7,6 +7,8 @@ import ( "strconv" "time" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/hashicorp/vault/api" platform "github.com/influxdata/influxdb/v2" ) @@ -125,7 +127,7 @@ func NewSecretService(cfgOpts ...ConfigOptFn) (*SecretService, error) { } // LoadSecret retrieves the secret value v found at key k for organization orgID. -func (s *SecretService) LoadSecret(ctx context.Context, orgID platform.ID, k string) (string, error) { +func (s *SecretService) LoadSecret(ctx context.Context, orgID platform2.ID, k string) (string, error) { data, _, err := s.loadSecrets(ctx, orgID) if err != nil { return "", err @@ -140,7 +142,7 @@ func (s *SecretService) LoadSecret(ctx context.Context, orgID platform.ID, k str // loadSecrets retrieves a map of secrets for an organization and the version of the secrets retrieved. // The version is used to ensure that concurrent updates will not overwrite one another. -func (s *SecretService) loadSecrets(ctx context.Context, orgID platform.ID) (map[string]string, int, error) { +func (s *SecretService) loadSecrets(ctx context.Context, orgID platform2.ID) (map[string]string, int, error) { // TODO(desa): update url construction sec, err := s.Client.Logical().Read(fmt.Sprintf("/secret/data/%s", orgID)) if err != nil { @@ -194,7 +196,7 @@ func (s *SecretService) loadSecrets(ctx context.Context, orgID platform.ID) (map } // GetSecretKeys retrieves all secret keys that are stored for the organization orgID. -func (s *SecretService) GetSecretKeys(ctx context.Context, orgID platform.ID) ([]string, error) { +func (s *SecretService) GetSecretKeys(ctx context.Context, orgID platform2.ID) ([]string, error) { data, _, err := s.loadSecrets(ctx, orgID) if err != nil { return nil, err @@ -209,7 +211,7 @@ func (s *SecretService) GetSecretKeys(ctx context.Context, orgID platform.ID) ([ } // PutSecret stores the secret pair (k,v) for the organization orgID. -func (s *SecretService) PutSecret(ctx context.Context, orgID platform.ID, k string, v string) error { +func (s *SecretService) PutSecret(ctx context.Context, orgID platform2.ID, k string, v string) error { data, ver, err := s.loadSecrets(ctx, orgID) if err != nil { return err @@ -225,7 +227,7 @@ func (s *SecretService) PutSecret(ctx context.Context, orgID platform.ID, k stri // If version is 0, the write will only be allowed if the keys do not exists. // If version is non-zero, the write will only be allowed if the keys current // version in vault matches the version specified. -func (s *SecretService) putSecrets(ctx context.Context, orgID platform.ID, data map[string]string, version int) error { +func (s *SecretService) putSecrets(ctx context.Context, orgID platform2.ID, data map[string]string, version int) error { m := map[string]interface{}{"data": data} if version >= 0 { @@ -240,12 +242,12 @@ func (s *SecretService) putSecrets(ctx context.Context, orgID platform.ID, data } // PutSecrets puts all provided secrets and overwrites any previous values. -func (s *SecretService) PutSecrets(ctx context.Context, orgID platform.ID, m map[string]string) error { +func (s *SecretService) PutSecrets(ctx context.Context, orgID platform2.ID, m map[string]string) error { return s.putSecrets(ctx, orgID, m, -1) } // PatchSecrets patches all provided secrets and updates any previous values. -func (s *SecretService) PatchSecrets(ctx context.Context, orgID platform.ID, m map[string]string) error { +func (s *SecretService) PatchSecrets(ctx context.Context, orgID platform2.ID, m map[string]string) error { data, ver, err := s.loadSecrets(ctx, orgID) if err != nil { return err @@ -259,7 +261,7 @@ func (s *SecretService) PatchSecrets(ctx context.Context, orgID platform.ID, m m } // DeleteSecret removes a single secret from the secret store. -func (s *SecretService) DeleteSecret(ctx context.Context, orgID platform.ID, ks ...string) error { +func (s *SecretService) DeleteSecret(ctx context.Context, orgID platform2.ID, ks ...string) error { data, ver, err := s.loadSecrets(ctx, orgID) if err != nil { return err diff --git a/write/batcher_test.go b/write/batcher_test.go index f0c24cab557..7d40583b700 100644 --- a/write/batcher_test.go +++ b/write/batcher_test.go @@ -11,6 +11,8 @@ import ( "testing" "time" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + "github.com/google/go-cmp/cmp" platform "github.com/influxdata/influxdb/v2" "github.com/influxdata/influxdb/v2/mock" @@ -175,8 +177,8 @@ func TestBatcher_write(t *testing.T) { type args struct { cancel bool writeError bool - org platform.ID - bucket platform.ID + org platform2.ID + bucket platform2.ID line string lines chan []byte errC chan error @@ -195,8 +197,8 @@ func TestBatcher_write(t *testing.T) { MaxFlushBytes: 1, }, args: args{ - org: platform.ID(1), - bucket: platform.ID(2), + org: platform2.ID(1), + bucket: platform2.ID(2), line: "m1,t1=v1 f1=1", lines: make(chan []byte), errC: make(chan error), @@ -209,8 +211,8 @@ func TestBatcher_write(t *testing.T) { MaxFlushInterval: time.Millisecond, }, args: args{ - org: platform.ID(1), - bucket: platform.ID(2), + org: platform2.ID(1), + bucket: platform2.ID(2), line: "m1,t1=v1 f1=1", lines: make(chan []byte), errC: make(chan error), @@ -224,8 +226,8 @@ func TestBatcher_write(t *testing.T) { }, args: args{ writeError: true, - org: platform.ID(1), - bucket: platform.ID(2), + org: platform2.ID(1), + bucket: platform2.ID(2), line: "m1,t1=v1 f1=1", lines: make(chan []byte), errC: make(chan error), @@ -239,8 +241,8 @@ func TestBatcher_write(t *testing.T) { }, args: args{ cancel: true, - org: platform.ID(1), - bucket: platform.ID(2), + org: platform2.ID(1), + bucket: platform2.ID(2), line: "m1,t1=v1 f1=1", lines: make(chan []byte, 1), errC: make(chan error, 1), @@ -255,8 +257,8 @@ func TestBatcher_write(t *testing.T) { }, args: args{ writeError: true, - org: platform.ID(1), - bucket: platform.ID(2), + org: platform2.ID(1), + bucket: platform2.ID(2), line: "m1,t1=v1 f1=1", lines: make(chan []byte), errC: make(chan error), @@ -269,8 +271,8 @@ func TestBatcher_write(t *testing.T) { MaxFlushBytes: 1, }, args: args{ - org: platform.ID(1), - bucket: platform.ID(2), + org: platform2.ID(1), + bucket: platform2.ID(2), line: "\n", lines: make(chan []byte), errC: make(chan error), @@ -357,8 +359,8 @@ func TestBatcher_WriteTo(t *testing.T) { } type args struct { writeError bool - org platform.ID - bucket platform.ID + org platform2.ID + bucket platform2.ID r func() io.Reader } tests := []struct { @@ -375,8 +377,8 @@ func TestBatcher_WriteTo(t *testing.T) { MaxFlushBytes: 1, }, args: args{ - org: platform.ID(1), - bucket: platform.ID(2), + org: platform2.ID(1), + bucket: platform2.ID(2), r: createReader("m1,t1=v1 f1=1"), }, want: "m1,t1=v1 f1=1", @@ -388,8 +390,8 @@ func TestBatcher_WriteTo(t *testing.T) { MaxFlushBytes: len([]byte("m1,t1=v1 f1=1\n")), }, args: args{ - org: platform.ID(1), - bucket: platform.ID(2), + org: platform2.ID(1), + bucket: platform2.ID(2), r: createReader("m1,t1=v1 f1=1\nm2,t2=v2 f2=2\nm3,t3=v3 f3=3"), }, want: "m3,t3=v3 f3=3", @@ -399,8 +401,8 @@ func TestBatcher_WriteTo(t *testing.T) { name: "errors during read return error", fields: fields{}, args: args{ - org: platform.ID(1), - bucket: platform.ID(2), + org: platform2.ID(1), + bucket: platform2.ID(2), r: createReader("error"), }, wantErr: true, @@ -493,8 +495,8 @@ func TestBatcher_WriteTo(t *testing.T) { func TestBatcher_WriteTimeout(t *testing.T) { // mocking the write service here to either return an error // or get back all the bytes from the reader. - bucketId := platform.ID(2) - orgId := platform.ID(1) + bucketId := platform2.ID(2) + orgId := platform2.ID(1) var got string svc := &mock.WriteService{ diff --git a/zap/auth_service.go b/zap/auth_service.go index c24d022238d..ac1b019b7d6 100644 --- a/zap/auth_service.go +++ b/zap/auth_service.go @@ -3,6 +3,8 @@ package zap import ( "context" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + platform "github.com/influxdata/influxdb/v2" "go.uber.org/zap" ) @@ -16,7 +18,7 @@ type AuthorizationService struct { } // FindAuthorizationByID returns an authorization given an id, and logs any errors. -func (s *AuthorizationService) FindAuthorizationByID(ctx context.Context, id platform.ID) (a *platform.Authorization, err error) { +func (s *AuthorizationService) FindAuthorizationByID(ctx context.Context, id platform2.ID) (a *platform.Authorization, err error) { defer func() { if err != nil { s.log.Info("Error finding authorization by id", zap.Error(err)) @@ -60,7 +62,7 @@ func (s *AuthorizationService) CreateAuthorization(ctx context.Context, a *platf } // DeleteAuthorization deletes an authorization, and logs any errors. -func (s *AuthorizationService) DeleteAuthorization(ctx context.Context, id platform.ID) (err error) { +func (s *AuthorizationService) DeleteAuthorization(ctx context.Context, id platform2.ID) (err error) { defer func() { if err != nil { s.log.Info("Error deleting authorization", zap.Error(err)) @@ -71,7 +73,7 @@ func (s *AuthorizationService) DeleteAuthorization(ctx context.Context, id platf } // UpdateAuthorization updates an authorization's status, description and logs any errors. -func (s *AuthorizationService) UpdateAuthorization(ctx context.Context, id platform.ID, upd *platform.AuthorizationUpdate) (a *platform.Authorization, err error) { +func (s *AuthorizationService) UpdateAuthorization(ctx context.Context, id platform2.ID, upd *platform.AuthorizationUpdate) (a *platform.Authorization, err error) { defer func() { if err != nil { s.log.Info("Error updating authorization", zap.Error(err)) diff --git a/zap/tracer.go b/zap/tracer.go index ade475ab095..43f5028e38d 100644 --- a/zap/tracer.go +++ b/zap/tracer.go @@ -8,7 +8,8 @@ import ( "net/http" "time" - platform "github.com/influxdata/influxdb/v2" + platform2 "github.com/influxdata/influxdb/v2/kit/platform" + opentracing "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/log" "go.uber.org/zap" @@ -30,10 +31,10 @@ const ( // Tracer implements opentracing.Tracer and logs each span as its own log. type Tracer struct { log *zap.Logger - idGenerator platform.IDGenerator + idGenerator platform2.IDGenerator } -func NewTracer(log *zap.Logger, idGenerator platform.IDGenerator) *Tracer { +func NewTracer(log *zap.Logger, idGenerator platform2.IDGenerator) *Tracer { return &Tracer{ log: log, idGenerator: idGenerator, @@ -265,8 +266,8 @@ func (s *Span) Log(data opentracing.LogData) { // SpanContext implements opentracing.SpanContext, all span contexts must be created using the Tracer. type SpanContext struct { - traceID platform.ID - spanID platform.ID + traceID platform2.ID + spanID platform2.ID baggage map[string]string } @@ -286,8 +287,8 @@ func (c SpanContext) ForeachBaggageItem(handler func(k, v string) bool) { func (c SpanContext) MarshalJSON() ([]byte, error) { raw := struct { - TraceID platform.ID `json:"trace_id"` - SpanID platform.ID `json:"span_id"` + TraceID platform2.ID `json:"trace_id"` + SpanID platform2.ID `json:"span_id"` Baggage map[string]string `json:"baggage"` }{ TraceID: c.traceID, @@ -299,8 +300,8 @@ func (c SpanContext) MarshalJSON() ([]byte, error) { func (c *SpanContext) UnmarshalJSON(data []byte) error { raw := struct { - TraceID platform.ID `json:"trace_id"` - SpanID platform.ID `json:"span_id"` + TraceID platform2.ID `json:"trace_id"` + SpanID platform2.ID `json:"span_id"` Baggage map[string]string `json:"baggage"` }{ TraceID: c.traceID,