diff --git a/apiserver/controllers/gitea_credentials.go b/apiserver/controllers/gitea_credentials.go new file mode 100644 index 00000000..e1be0fb7 --- /dev/null +++ b/apiserver/controllers/gitea_credentials.go @@ -0,0 +1,228 @@ +package controllers + +import ( + "encoding/json" + "log/slog" + "math" + "net/http" + "strconv" + + "github.com/gorilla/mux" + + gErrors "github.com/cloudbase/garm-provider-common/errors" + "github.com/cloudbase/garm/params" +) + +// swagger:route GET /gitea/credentials credentials ListGiteaCredentials +// +// List all credentials. +// +// Responses: +// 200: Credentials +// 400: APIErrorResponse +func (a *APIController) ListGiteaCredentials(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + creds, err := a.r.ListGiteaCredentials(ctx) + if err != nil { + handleError(ctx, w, err) + return + } + + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(creds); err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to encode response") + } +} + +// swagger:route POST /gitea/credentials credentials CreateGiteaCredentials +// +// Create a Gitea credential. +// +// Parameters: +// + name: Body +// description: Parameters used when creating a Gitea credential. +// type: CreateGiteaCredentialsParams +// in: body +// required: true +// +// Responses: +// 200: ForgeCredentials +// 400: APIErrorResponse +func (a *APIController) CreateGiteaCredential(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var params params.CreateGiteaCredentialsParams + if err := json.NewDecoder(r.Body).Decode(¶ms); err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to decode request") + handleError(ctx, w, gErrors.ErrBadRequest) + return + } + + cred, err := a.r.CreateGiteaCredentials(ctx, params) + if err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to create Gitea credential") + handleError(ctx, w, err) + return + } + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(cred); err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to encode response") + } +} + +// swagger:route GET /gitea/credentials/{id} credentials GetGiteaCredentials +// +// Get a Gitea credential. +// +// Parameters: +// + name: id +// description: ID of the Gitea credential. +// type: integer +// in: path +// required: true +// +// Responses: +// 200: ForgeCredentials +// 400: APIErrorResponse +func (a *APIController) GetGiteaCredential(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + vars := mux.Vars(r) + idParam, ok := vars["id"] + if !ok { + slog.ErrorContext(ctx, "missing id in request") + handleError(ctx, w, gErrors.ErrBadRequest) + return + } + + id, err := strconv.ParseUint(idParam, 10, 64) + if err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to parse id") + handleError(ctx, w, gErrors.ErrBadRequest) + return + } + + if id > math.MaxUint { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "id is too large") + handleError(ctx, w, gErrors.ErrBadRequest) + return + } + + cred, err := a.r.GetGiteaCredentials(ctx, uint(id)) + if err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to get Gitea credential") + handleError(ctx, w, err) + return + } + + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(cred); err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to encode response") + } +} + +// swagger:route DELETE /gitea/credentials/{id} credentials DeleteGiteaCredentials +// +// Delete a Gitea credential. +// +// Parameters: +// + name: id +// description: ID of the Gitea credential. +// type: integer +// in: path +// required: true +// +// Responses: +// default: APIErrorResponse +func (a *APIController) DeleteGiteaCredential(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + vars := mux.Vars(r) + idParam, ok := vars["id"] + if !ok { + slog.ErrorContext(ctx, "missing id in request") + handleError(ctx, w, gErrors.ErrBadRequest) + return + } + + id, err := strconv.ParseUint(idParam, 10, 64) + if err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to parse id") + handleError(ctx, w, gErrors.ErrBadRequest) + return + } + + if id > math.MaxUint { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "id is too large") + handleError(ctx, w, gErrors.ErrBadRequest) + return + } + + if err := a.r.DeleteGiteaCredentials(ctx, uint(id)); err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to delete Gitea credential") + handleError(ctx, w, err) + return + } + + w.WriteHeader(http.StatusNoContent) +} + +// swagger:route PUT /gitea/credentials/{id} credentials UpdateGiteaCredentials +// +// Update a Gitea credential. +// +// Parameters: +// + name: id +// description: ID of the Gitea credential. +// type: integer +// in: path +// required: true +// + name: Body +// description: Parameters used when updating a Gitea credential. +// type: UpdateGiteaCredentialsParams +// in: body +// required: true +// +// Responses: +// 200: ForgeCredentials +// 400: APIErrorResponse +func (a *APIController) UpdateGiteaCredential(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + vars := mux.Vars(r) + idParam, ok := vars["id"] + if !ok { + slog.ErrorContext(ctx, "missing id in request") + handleError(ctx, w, gErrors.ErrBadRequest) + return + } + + id, err := strconv.ParseUint(idParam, 10, 64) + if err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to parse id") + handleError(ctx, w, gErrors.ErrBadRequest) + return + } + + if id > math.MaxUint { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "id is too large") + handleError(ctx, w, gErrors.ErrBadRequest) + return + } + + var params params.UpdateGiteaCredentialsParams + if err := json.NewDecoder(r.Body).Decode(¶ms); err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to decode request") + handleError(ctx, w, gErrors.ErrBadRequest) + return + } + + cred, err := a.r.UpdateGiteaCredentials(ctx, uint(id), params) + if err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to update Gitea credential") + handleError(ctx, w, err) + return + } + + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(cred); err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to encode response") + } +} diff --git a/apiserver/controllers/gitea_endpoints.go b/apiserver/controllers/gitea_endpoints.go new file mode 100644 index 00000000..6f1525d5 --- /dev/null +++ b/apiserver/controllers/gitea_endpoints.go @@ -0,0 +1,186 @@ +package controllers + +import ( + "encoding/json" + "log/slog" + "net/http" + + "github.com/gorilla/mux" + + gErrors "github.com/cloudbase/garm-provider-common/errors" + "github.com/cloudbase/garm/params" +) + +// swagger:route POST /gitea/endpoints endpoints CreateGiteaEndpoint +// +// Create a Gitea Endpoint. +// +// Parameters: +// + name: Body +// description: Parameters used when creating a Gitea endpoint. +// type: CreateGiteaEndpointParams +// in: body +// required: true +// +// Responses: +// 200: ForgeEndpoint +// default: APIErrorResponse +func (a *APIController) CreateGiteaEndpoint(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var params params.CreateGiteaEndpointParams + if err := json.NewDecoder(r.Body).Decode(¶ms); err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to decode request") + handleError(ctx, w, gErrors.ErrBadRequest) + return + } + + endpoint, err := a.r.CreateGiteaEndpoint(ctx, params) + if err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to create Gitea endpoint") + handleError(ctx, w, err) + return + } + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(endpoint); err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to encode response") + } +} + +// swagger:route GET /gitea/endpoints endpoints ListGiteaEndpoints +// +// List all Gitea Endpoints. +// +// Responses: +// 200: ForgeEndpoints +// default: APIErrorResponse +func (a *APIController) ListGiteaEndpoints(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + endpoints, err := a.r.ListGiteaEndpoints(ctx) + if err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to list Gitea endpoints") + handleError(ctx, w, err) + return + } + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(endpoints); err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to encode response") + } +} + +// swagger:route GET /gitea/endpoints/{name} endpoints GetGiteaEndpoint +// +// Get a Gitea Endpoint. +// +// Parameters: +// + name: name +// description: The name of the Gitea endpoint. +// type: string +// in: path +// required: true +// +// Responses: +// 200: ForgeEndpoint +// default: APIErrorResponse +func (a *APIController) GetGiteaEndpoint(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + vars := mux.Vars(r) + name, ok := vars["name"] + if !ok { + slog.ErrorContext(ctx, "missing name in request") + handleError(ctx, w, gErrors.ErrBadRequest) + return + } + endpoint, err := a.r.GetGiteaEndpoint(ctx, name) + if err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to get Gitea endpoint") + handleError(ctx, w, err) + return + } + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(endpoint); err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to encode response") + } +} + +// swagger:route DELETE /gitea/endpoints/{name} endpoints DeleteGiteaEndpoint +// +// Delete a Gitea Endpoint. +// +// Parameters: +// + name: name +// description: The name of the Gitea endpoint. +// type: string +// in: path +// required: true +// +// Responses: +// default: APIErrorResponse +func (a *APIController) DeleteGiteaEndpoint(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + vars := mux.Vars(r) + name, ok := vars["name"] + if !ok { + slog.ErrorContext(ctx, "missing name in request") + handleError(ctx, w, gErrors.ErrBadRequest) + return + } + if err := a.r.DeleteGiteaEndpoint(ctx, name); err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to delete Gitea endpoint") + handleError(ctx, w, err) + return + } + w.WriteHeader(http.StatusNoContent) +} + +// swagger:route PUT /gitea/endpoints/{name} endpoints UpdateGiteaEndpoint +// +// Update a Gitea Endpoint. +// +// Parameters: +// + name: name +// description: The name of the Gitea endpoint. +// type: string +// in: path +// required: true +// + name: Body +// description: Parameters used when updating a Gitea endpoint. +// type: UpdateGiteaEndpointParams +// in: body +// required: true +// +// Responses: +// 200: ForgeEndpoint +// default: APIErrorResponse +func (a *APIController) UpdateGiteaEndpoint(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + vars := mux.Vars(r) + name, ok := vars["name"] + if !ok { + slog.ErrorContext(ctx, "missing name in request") + handleError(ctx, w, gErrors.ErrBadRequest) + return + } + + var params params.UpdateGiteaEndpointParams + if err := json.NewDecoder(r.Body).Decode(¶ms); err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to decode request") + handleError(ctx, w, gErrors.ErrBadRequest) + return + } + + endpoint, err := a.r.UpdateGiteaEndpoint(ctx, name, params) + if err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to update GitHub endpoint") + handleError(ctx, w, err) + return + } + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(endpoint); err != nil { + slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to encode response") + } +} diff --git a/apiserver/controllers/credentials.go b/apiserver/controllers/github_credentials.go similarity index 98% rename from apiserver/controllers/credentials.go rename to apiserver/controllers/github_credentials.go index 70869b54..c7544357 100644 --- a/apiserver/controllers/credentials.go +++ b/apiserver/controllers/github_credentials.go @@ -47,7 +47,7 @@ func (a *APIController) ListCredentials(w http.ResponseWriter, r *http.Request) // required: true // // Responses: -// 200: GithubCredentials +// 200: ForgeCredentials // 400: APIErrorResponse func (a *APIController) CreateGithubCredential(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -83,7 +83,7 @@ func (a *APIController) CreateGithubCredential(w http.ResponseWriter, r *http.Re // required: true // // Responses: -// 200: GithubCredentials +// 200: ForgeCredentials // 400: APIErrorResponse func (a *APIController) GetGithubCredential(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -183,7 +183,7 @@ func (a *APIController) DeleteGithubCredential(w http.ResponseWriter, r *http.Re // required: true // // Responses: -// 200: GithubCredentials +// 200: ForgeCredentials // 400: APIErrorResponse func (a *APIController) UpdateGithubCredential(w http.ResponseWriter, r *http.Request) { ctx := r.Context() diff --git a/apiserver/controllers/endpoints.go b/apiserver/controllers/github_endpoints.go similarity index 98% rename from apiserver/controllers/endpoints.go rename to apiserver/controllers/github_endpoints.go index 81e984d4..491c5716 100644 --- a/apiserver/controllers/endpoints.go +++ b/apiserver/controllers/github_endpoints.go @@ -23,7 +23,7 @@ import ( // required: true // // Responses: -// 200: GithubEndpoint +// 200: ForgeEndpoint // default: APIErrorResponse func (a *APIController) CreateGithubEndpoint(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -52,7 +52,7 @@ func (a *APIController) CreateGithubEndpoint(w http.ResponseWriter, r *http.Requ // List all GitHub Endpoints. // // Responses: -// 200: GithubEndpoints +// 200: ForgeEndpoints // default: APIErrorResponse func (a *APIController) ListGithubEndpoints(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -81,7 +81,7 @@ func (a *APIController) ListGithubEndpoints(w http.ResponseWriter, r *http.Reque // required: true // // Responses: -// 200: GithubEndpoint +// 200: ForgeEndpoint // default: APIErrorResponse func (a *APIController) GetGithubEndpoint(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -153,7 +153,7 @@ func (a *APIController) DeleteGithubEndpoint(w http.ResponseWriter, r *http.Requ // required: true // // Responses: -// 200: GithubEndpoint +// 200: ForgeEndpoint // default: APIErrorResponse func (a *APIController) UpdateGithubEndpoint(w http.ResponseWriter, r *http.Request) { ctx := r.Context() diff --git a/apiserver/routers/routers.go b/apiserver/routers/routers.go index ec135292..2036b5f1 100644 --- a/apiserver/routers/routers.go +++ b/apiserver/routers/routers.go @@ -454,6 +454,44 @@ func NewAPIRouter(han *controllers.APIController, authMiddleware, initMiddleware apiRouter.Handle("/github/credentials/{id}/", http.HandlerFunc(han.UpdateGithubCredential)).Methods("PUT", "OPTIONS") apiRouter.Handle("/github/credentials/{id}", http.HandlerFunc(han.UpdateGithubCredential)).Methods("PUT", "OPTIONS") + ////////////////////// + // Gitea Endpoints // + ////////////////////// + // Create Gitea Endpoint + apiRouter.Handle("/gitea/endpoints/", http.HandlerFunc(han.CreateGiteaEndpoint)).Methods("POST", "OPTIONS") + apiRouter.Handle("/gitea/endpoints", http.HandlerFunc(han.CreateGiteaEndpoint)).Methods("POST", "OPTIONS") + // List Gitea Endpoints + apiRouter.Handle("/gitea/endpoints/", http.HandlerFunc(han.ListGiteaEndpoints)).Methods("GET", "OPTIONS") + apiRouter.Handle("/gitea/endpoints", http.HandlerFunc(han.ListGiteaEndpoints)).Methods("GET", "OPTIONS") + // Get Gitea Endpoint + apiRouter.Handle("/gitea/endpoints/{name}/", http.HandlerFunc(han.GetGiteaEndpoint)).Methods("GET", "OPTIONS") + apiRouter.Handle("/gitea/endpoints/{name}", http.HandlerFunc(han.GetGiteaEndpoint)).Methods("GET", "OPTIONS") + // Delete Gitea Endpoint + apiRouter.Handle("/gitea/endpoints/{name}/", http.HandlerFunc(han.DeleteGiteaEndpoint)).Methods("DELETE", "OPTIONS") + apiRouter.Handle("/gitea/endpoints/{name}", http.HandlerFunc(han.DeleteGiteaEndpoint)).Methods("DELETE", "OPTIONS") + // Update Gitea Endpoint + apiRouter.Handle("/gitea/endpoints/{name}/", http.HandlerFunc(han.UpdateGiteaEndpoint)).Methods("PUT", "OPTIONS") + apiRouter.Handle("/gitea/endpoints/{name}", http.HandlerFunc(han.UpdateGiteaEndpoint)).Methods("PUT", "OPTIONS") + + //////////////////////// + // Gitea credentials // + //////////////////////// + // List Gitea Credentials + apiRouter.Handle("/gitea/credentials/", http.HandlerFunc(han.ListGiteaCredentials)).Methods("GET", "OPTIONS") + apiRouter.Handle("/gitea/credentials", http.HandlerFunc(han.ListGiteaCredentials)).Methods("GET", "OPTIONS") + // Create Gitea Credentials + apiRouter.Handle("/gitea/credentials/", http.HandlerFunc(han.CreateGiteaCredential)).Methods("POST", "OPTIONS") + apiRouter.Handle("/gitea/credentials", http.HandlerFunc(han.CreateGiteaCredential)).Methods("POST", "OPTIONS") + // Get Gitea Credential + apiRouter.Handle("/gitea/credentials/{id}/", http.HandlerFunc(han.GetGiteaCredential)).Methods("GET", "OPTIONS") + apiRouter.Handle("/gitea/credentials/{id}", http.HandlerFunc(han.GetGiteaCredential)).Methods("GET", "OPTIONS") + // Delete Gitea Credential + apiRouter.Handle("/gitea/credentials/{id}/", http.HandlerFunc(han.DeleteGiteaCredential)).Methods("DELETE", "OPTIONS") + apiRouter.Handle("/gitea/credentials/{id}", http.HandlerFunc(han.DeleteGiteaCredential)).Methods("DELETE", "OPTIONS") + // Update Gitea Credential + apiRouter.Handle("/gitea/credentials/{id}/", http.HandlerFunc(han.UpdateGiteaCredential)).Methods("PUT", "OPTIONS") + apiRouter.Handle("/gitea/credentials/{id}", http.HandlerFunc(han.UpdateGiteaCredential)).Methods("PUT", "OPTIONS") + ///////////////////////// // Websocket endpoints // ///////////////////////// diff --git a/apiserver/swagger-models.yaml b/apiserver/swagger-models.yaml index ad83d6c8..74eaac84 100644 --- a/apiserver/swagger-models.yaml +++ b/apiserver/swagger-models.yaml @@ -74,11 +74,11 @@ definitions: package: github.com/cloudbase/garm/params alias: garm_params items: - $ref: '#/definitions/GithubCredentials' - GithubCredentials: + $ref: '#/definitions/ForgeCredentials' + ForgeCredentials: type: object x-go-type: - type: GithubCredentials + type: ForgeCredentials import: package: github.com/cloudbase/garm/params alias: garm_params @@ -271,22 +271,29 @@ definitions: import: package: github.com/cloudbase/garm/params alias: garm_params - GithubEndpoint: + UpdateGiteaEndpointParams: type: object x-go-type: - type: GithubEndpoint + type: UpdateGiteaEndpointParams import: package: github.com/cloudbase/garm/params alias: garm_params - GithubEndpoints: + ForgeEndpoint: + type: object + x-go-type: + type: ForgeEndpoint + import: + package: github.com/cloudbase/garm/params + alias: garm_params + ForgeEndpoints: type: array x-go-type: - type: GithubEndpoints + type: ForgeEndpoints import: package: github.com/cloudbase/garm/params alias: garm_params items: - $ref: '#/definitions/GithubEndpoint' + $ref: '#/definitions/ForgeEndpoint' CreateGithubEndpointParams: type: object x-go-type: @@ -294,6 +301,13 @@ definitions: import: package: github.com/cloudbase/garm/params alias: garm_params + CreateGiteaEndpointParams: + type: object + x-go-type: + type: CreateGiteaEndpointParams + import: + package: github.com/cloudbase/garm/params + alias: garm_params CreateGithubCredentialsParams: type: object x-go-type: @@ -301,6 +315,13 @@ definitions: import: package: github.com/cloudbase/garm/params alias: garm_params + CreateGiteaCredentialsParams: + type: object + x-go-type: + type: CreateGiteaCredentialsParams + import: + package: github.com/cloudbase/garm/params + alias: garm_params UpdateGithubCredentialsParams: type: object x-go-type: @@ -308,6 +329,13 @@ definitions: import: package: github.com/cloudbase/garm/params alias: garm_params + UpdateGiteaCredentialsParams: + type: object + x-go-type: + type: UpdateGiteaCredentialsParams + import: + package: github.com/cloudbase/garm/params + alias: garm_params UpdateControllerParams: type: object x-go-type: diff --git a/apiserver/swagger.yaml b/apiserver/swagger.yaml index 2f89ab77..66e7a655 100644 --- a/apiserver/swagger.yaml +++ b/apiserver/swagger.yaml @@ -23,6 +23,20 @@ definitions: alias: garm_params package: github.com/cloudbase/garm/params type: CreateEnterpriseParams + CreateGiteaCredentialsParams: + type: object + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: CreateGiteaCredentialsParams + CreateGiteaEndpointParams: + type: object + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: CreateGiteaEndpointParams CreateGithubCredentialsParams: type: object x-go-type: @@ -74,7 +88,7 @@ definitions: type: CreateScaleSetParams Credentials: items: - $ref: '#/definitions/GithubCredentials' + $ref: '#/definitions/ForgeCredentials' type: array x-go-type: import: @@ -97,29 +111,29 @@ definitions: alias: garm_params package: github.com/cloudbase/garm/params type: Enterprises - GithubCredentials: + ForgeCredentials: type: object x-go-type: import: alias: garm_params package: github.com/cloudbase/garm/params - type: GithubCredentials - GithubEndpoint: + type: ForgeCredentials + ForgeEndpoint: type: object x-go-type: import: alias: garm_params package: github.com/cloudbase/garm/params - type: GithubEndpoint - GithubEndpoints: + type: ForgeEndpoint + ForgeEndpoints: items: - $ref: '#/definitions/GithubEndpoint' + $ref: '#/definitions/ForgeEndpoint' type: array x-go-type: import: alias: garm_params package: github.com/cloudbase/garm/params - type: GithubEndpoints + type: ForgeEndpoints HookInfo: type: object x-go-type: @@ -281,6 +295,20 @@ definitions: alias: garm_params package: github.com/cloudbase/garm/params type: UpdateEntityParams + UpdateGiteaCredentialsParams: + type: object + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: UpdateGiteaCredentialsParams + UpdateGiteaEndpointParams: + type: object + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: UpdateGiteaEndpointParams UpdateGithubCredentialsParams: type: object x-go-type: @@ -721,6 +749,212 @@ paths: summary: Initialize the first run of the controller. tags: - first-run + /gitea/credentials: + get: + operationId: ListGiteaCredentials + responses: + "200": + description: Credentials + schema: + $ref: '#/definitions/Credentials' + "400": + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: List all credentials. + tags: + - credentials + post: + operationId: CreateGiteaCredentials + parameters: + - description: Parameters used when creating a Gitea credential. + in: body + name: Body + required: true + schema: + $ref: '#/definitions/CreateGiteaCredentialsParams' + description: Parameters used when creating a Gitea credential. + type: object + responses: + "200": + description: ForgeCredentials + schema: + $ref: '#/definitions/ForgeCredentials' + "400": + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Create a Gitea credential. + tags: + - credentials + /gitea/credentials/{id}: + delete: + operationId: DeleteGiteaCredentials + parameters: + - description: ID of the Gitea credential. + in: path + name: id + required: true + type: integer + responses: + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Delete a Gitea credential. + tags: + - credentials + get: + operationId: GetGiteaCredentials + parameters: + - description: ID of the Gitea credential. + in: path + name: id + required: true + type: integer + responses: + "200": + description: ForgeCredentials + schema: + $ref: '#/definitions/ForgeCredentials' + "400": + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Get a Gitea credential. + tags: + - credentials + put: + operationId: UpdateGiteaCredentials + parameters: + - description: ID of the Gitea credential. + in: path + name: id + required: true + type: integer + - description: Parameters used when updating a Gitea credential. + in: body + name: Body + required: true + schema: + $ref: '#/definitions/UpdateGiteaCredentialsParams' + description: Parameters used when updating a Gitea credential. + type: object + responses: + "200": + description: ForgeCredentials + schema: + $ref: '#/definitions/ForgeCredentials' + "400": + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Update a Gitea credential. + tags: + - credentials + /gitea/endpoints: + get: + operationId: ListGiteaEndpoints + responses: + "200": + description: ForgeEndpoints + schema: + $ref: '#/definitions/ForgeEndpoints' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: List all Gitea Endpoints. + tags: + - endpoints + post: + operationId: CreateGiteaEndpoint + parameters: + - description: Parameters used when creating a Gitea endpoint. + in: body + name: Body + required: true + schema: + $ref: '#/definitions/CreateGiteaEndpointParams' + description: Parameters used when creating a Gitea endpoint. + type: object + responses: + "200": + description: ForgeEndpoint + schema: + $ref: '#/definitions/ForgeEndpoint' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Create a Gitea Endpoint. + tags: + - endpoints + /gitea/endpoints/{name}: + delete: + operationId: DeleteGiteaEndpoint + parameters: + - description: The name of the Gitea endpoint. + in: path + name: name + required: true + type: string + responses: + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Delete a Gitea Endpoint. + tags: + - endpoints + get: + operationId: GetGiteaEndpoint + parameters: + - description: The name of the Gitea endpoint. + in: path + name: name + required: true + type: string + responses: + "200": + description: ForgeEndpoint + schema: + $ref: '#/definitions/ForgeEndpoint' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Get a Gitea Endpoint. + tags: + - endpoints + put: + operationId: UpdateGiteaEndpoint + parameters: + - description: The name of the Gitea endpoint. + in: path + name: name + required: true + type: string + - description: Parameters used when updating a Gitea endpoint. + in: body + name: Body + required: true + schema: + $ref: '#/definitions/UpdateGiteaEndpointParams' + description: Parameters used when updating a Gitea endpoint. + type: object + responses: + "200": + description: ForgeEndpoint + schema: + $ref: '#/definitions/ForgeEndpoint' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Update a Gitea Endpoint. + tags: + - endpoints /github/credentials: get: operationId: ListCredentials @@ -749,9 +983,9 @@ paths: type: object responses: "200": - description: GithubCredentials + description: ForgeCredentials schema: - $ref: '#/definitions/GithubCredentials' + $ref: '#/definitions/ForgeCredentials' "400": description: APIErrorResponse schema: @@ -786,9 +1020,9 @@ paths: type: integer responses: "200": - description: GithubCredentials + description: ForgeCredentials schema: - $ref: '#/definitions/GithubCredentials' + $ref: '#/definitions/ForgeCredentials' "400": description: APIErrorResponse schema: @@ -814,9 +1048,9 @@ paths: type: object responses: "200": - description: GithubCredentials + description: ForgeCredentials schema: - $ref: '#/definitions/GithubCredentials' + $ref: '#/definitions/ForgeCredentials' "400": description: APIErrorResponse schema: @@ -829,9 +1063,9 @@ paths: operationId: ListGithubEndpoints responses: "200": - description: GithubEndpoints + description: ForgeEndpoints schema: - $ref: '#/definitions/GithubEndpoints' + $ref: '#/definitions/ForgeEndpoints' default: description: APIErrorResponse schema: @@ -852,9 +1086,9 @@ paths: type: object responses: "200": - description: GithubEndpoint + description: ForgeEndpoint schema: - $ref: '#/definitions/GithubEndpoint' + $ref: '#/definitions/ForgeEndpoint' default: description: APIErrorResponse schema: @@ -889,9 +1123,9 @@ paths: type: string responses: "200": - description: GithubEndpoint + description: ForgeEndpoint schema: - $ref: '#/definitions/GithubEndpoint' + $ref: '#/definitions/ForgeEndpoint' default: description: APIErrorResponse schema: @@ -917,9 +1151,9 @@ paths: type: object responses: "200": - description: GithubEndpoint + description: ForgeEndpoint schema: - $ref: '#/definitions/GithubEndpoint' + $ref: '#/definitions/ForgeEndpoint' default: description: APIErrorResponse schema: diff --git a/cache/cache_test.go b/cache/cache_test.go index 08b269b8..3e7ed559 100644 --- a/cache/cache_test.go +++ b/cache/cache_test.go @@ -30,7 +30,7 @@ func (c *CacheTestSuite) TearDownTest() { githubToolsCache.mux.Lock() defer githubToolsCache.mux.Unlock() githubToolsCache.entities = make(map[string]GithubEntityTools) - credentialsCache.cache = make(map[uint]params.GithubCredentials) + credentialsCache.cache = make(map[uint]params.ForgeCredentials) instanceCache.cache = make(map[string]params.Instance) entityCache = &EntityCache{ entities: make(map[string]EntityItem), @@ -90,7 +90,7 @@ func (c *CacheTestSuite) TestGetInexistentCache() { } func (c *CacheTestSuite) TestSetGithubCredentials() { - credentials := params.GithubCredentials{ + credentials := params.ForgeCredentials{ ID: 1, } SetGithubCredentials(credentials) @@ -100,7 +100,7 @@ func (c *CacheTestSuite) TestSetGithubCredentials() { } func (c *CacheTestSuite) TestGetGithubCredentials() { - credentials := params.GithubCredentials{ + credentials := params.ForgeCredentials{ ID: 1, } SetGithubCredentials(credentials) @@ -110,11 +110,11 @@ func (c *CacheTestSuite) TestGetGithubCredentials() { nonExisting, ok := GetGithubCredentials(2) c.Require().False(ok) - c.Require().Equal(params.GithubCredentials{}, nonExisting) + c.Require().Equal(params.ForgeCredentials{}, nonExisting) } func (c *CacheTestSuite) TestDeleteGithubCredentials() { - credentials := params.GithubCredentials{ + credentials := params.ForgeCredentials{ ID: 1, } SetGithubCredentials(credentials) @@ -125,14 +125,14 @@ func (c *CacheTestSuite) TestDeleteGithubCredentials() { DeleteGithubCredentials(1) cachedCreds, ok = GetGithubCredentials(1) c.Require().False(ok) - c.Require().Equal(params.GithubCredentials{}, cachedCreds) + c.Require().Equal(params.ForgeCredentials{}, cachedCreds) } func (c *CacheTestSuite) TestGetAllGithubCredentials() { - credentials1 := params.GithubCredentials{ + credentials1 := params.ForgeCredentials{ ID: 1, } - credentials2 := params.GithubCredentials{ + credentials2 := params.ForgeCredentials{ ID: 2, } SetGithubCredentials(credentials1) @@ -265,12 +265,12 @@ func (c *CacheTestSuite) TestSetGetEntityCache() { c.Require().True(ok) c.Require().Equal(entity.ID, cachedEntity.ID) - entity.Credentials.GithubCredentials.Description = "test description" + entity.Credentials.Description = "test description" SetEntity(entity) cachedEntity, ok = GetEntity("test-entity") c.Require().True(ok) c.Require().Equal(entity.ID, cachedEntity.ID) - c.Require().Equal(entity.Credentials.GithubCredentials.Description, cachedEntity.Credentials.GithubCredentials.Description) + c.Require().Equal(entity.Credentials.Description, cachedEntity.Credentials.Description) } func (c *CacheTestSuite) TestReplaceEntityPools() { @@ -280,10 +280,7 @@ func (c *CacheTestSuite) TestReplaceEntityPools() { Name: "test", Owner: "test", Credentials: params.ForgeCredentials{ - ForgeType: params.GithubEndpointType, - GithubCredentials: params.GithubCredentials{ - ID: 1, - }, + ID: 1, }, } pool1 := params.Pool{ @@ -293,7 +290,7 @@ func (c *CacheTestSuite) TestReplaceEntityPools() { ID: "pool-2", } - credentials := params.GithubCredentials{ + credentials := params.ForgeCredentials{ ID: 1, Name: "test", } @@ -304,7 +301,7 @@ func (c *CacheTestSuite) TestReplaceEntityPools() { cachedEntity, ok := GetEntity(entity.ID) c.Require().True(ok) c.Require().Equal(entity.ID, cachedEntity.ID) - c.Require().Equal("test", cachedEntity.Credentials.GithubCredentials.Name) + c.Require().Equal("test", cachedEntity.Credentials.Name) pools := GetEntityPools(entity.ID) c.Require().Len(pools, 2) diff --git a/cache/credentials_cache.go b/cache/credentials_cache.go index 060b076a..d5626f40 100644 --- a/cache/credentials_cache.go +++ b/cache/credentials_cache.go @@ -6,61 +6,67 @@ import ( "github.com/cloudbase/garm/params" ) -var credentialsCache *GithubCredentials +var credentialsCache *CredentialCache +var giteaCredentialsCache *CredentialCache func init() { - ghCredentialsCache := &GithubCredentials{ - cache: make(map[uint]params.GithubCredentials), + ghCredentialsCache := &CredentialCache{ + cache: make(map[uint]params.ForgeCredentials), } + gtCredentialsCache := &CredentialCache{ + cache: make(map[uint]params.ForgeCredentials), + } + credentialsCache = ghCredentialsCache + giteaCredentialsCache = gtCredentialsCache } -type GithubCredentials struct { +type CredentialCache struct { mux sync.Mutex - cache map[uint]params.GithubCredentials + cache map[uint]params.ForgeCredentials } -func (g *GithubCredentials) SetCredentialsRateLimit(credsID uint, rateLimit params.GithubRateLimit) { +func (g *CredentialCache) SetCredentialsRateLimit(credsID uint, rateLimit params.GithubRateLimit) { g.mux.Lock() defer g.mux.Unlock() if creds, ok := g.cache[credsID]; ok { - creds.RateLimit = rateLimit + creds.RateLimit = &rateLimit g.cache[credsID] = creds } } -func (g *GithubCredentials) SetCredentials(credentials params.GithubCredentials) { +func (g *CredentialCache) SetCredentials(credentials params.ForgeCredentials) { g.mux.Lock() defer g.mux.Unlock() g.cache[credentials.ID] = credentials - UpdateCredentialsInAffectedEntities(credentials.GetForgeCredentials()) + UpdateCredentialsInAffectedEntities(credentials) } -func (g *GithubCredentials) GetCredentials(id uint) (params.GithubCredentials, bool) { +func (g *CredentialCache) GetCredentials(id uint) (params.ForgeCredentials, bool) { g.mux.Lock() defer g.mux.Unlock() if creds, ok := g.cache[id]; ok { return creds, true } - return params.GithubCredentials{}, false + return params.ForgeCredentials{}, false } -func (g *GithubCredentials) DeleteCredentials(id uint) { +func (g *CredentialCache) DeleteCredentials(id uint) { g.mux.Lock() defer g.mux.Unlock() delete(g.cache, id) } -func (g *GithubCredentials) GetAllCredentials() []params.GithubCredentials { +func (g *CredentialCache) GetAllCredentials() []params.ForgeCredentials { g.mux.Lock() defer g.mux.Unlock() - creds := make([]params.GithubCredentials, 0, len(g.cache)) + creds := make([]params.ForgeCredentials, 0, len(g.cache)) for _, cred := range g.cache { creds = append(creds, cred) } @@ -70,11 +76,11 @@ func (g *GithubCredentials) GetAllCredentials() []params.GithubCredentials { return creds } -func (g *GithubCredentials) GetAllCredentialsAsMap() map[uint]params.GithubCredentials { +func (g *CredentialCache) GetAllCredentialsAsMap() map[uint]params.ForgeCredentials { g.mux.Lock() defer g.mux.Unlock() - creds := make(map[uint]params.GithubCredentials, len(g.cache)) + creds := make(map[uint]params.ForgeCredentials, len(g.cache)) for id, cred := range g.cache { creds[id] = cred } @@ -82,11 +88,11 @@ func (g *GithubCredentials) GetAllCredentialsAsMap() map[uint]params.GithubCrede return creds } -func SetGithubCredentials(credentials params.GithubCredentials) { +func SetGithubCredentials(credentials params.ForgeCredentials) { credentialsCache.SetCredentials(credentials) } -func GetGithubCredentials(id uint) (params.GithubCredentials, bool) { +func GetGithubCredentials(id uint) (params.ForgeCredentials, bool) { return credentialsCache.GetCredentials(id) } @@ -94,7 +100,7 @@ func DeleteGithubCredentials(id uint) { credentialsCache.DeleteCredentials(id) } -func GetAllGithubCredentials() []params.GithubCredentials { +func GetAllGithubCredentials() []params.ForgeCredentials { return credentialsCache.GetAllCredentials() } @@ -102,6 +108,26 @@ func SetCredentialsRateLimit(credsID uint, rateLimit params.GithubRateLimit) { credentialsCache.SetCredentialsRateLimit(credsID, rateLimit) } -func GetAllGithubCredentialsAsMap() map[uint]params.GithubCredentials { +func GetAllGithubCredentialsAsMap() map[uint]params.ForgeCredentials { return credentialsCache.GetAllCredentialsAsMap() } + +func SetGiteaCredentials(credentials params.ForgeCredentials) { + giteaCredentialsCache.SetCredentials(credentials) +} + +func GetGiteaCredentials(id uint) (params.ForgeCredentials, bool) { + return giteaCredentialsCache.GetCredentials(id) +} + +func DeleteGiteaCredentials(id uint) { + giteaCredentialsCache.DeleteCredentials(id) +} + +func GetAllGiteaCredentials() []params.ForgeCredentials { + return giteaCredentialsCache.GetAllCredentials() +} + +func GetAllGiteaCredentialsAsMap() map[uint]params.ForgeCredentials { + return giteaCredentialsCache.GetAllCredentialsAsMap() +} diff --git a/cache/entity_cache.go b/cache/entity_cache.go index 74f406de..6bd1f2c7 100644 --- a/cache/entity_cache.go +++ b/cache/entity_cache.go @@ -44,18 +44,16 @@ func (e *EntityCache) GetEntity(entityID string) (params.ForgeEntity, bool) { defer e.mux.Unlock() if cache, ok := e.entities[entityID]; ok { - // Get the credentials from the credentials cache. - var forgeCredsGetter params.ForgeCredentialsGetter - var credsOk bool + var creds params.ForgeCredentials + var ok bool switch cache.Entity.Credentials.ForgeType { case params.GithubEndpointType: - forgeCredsGetter, credsOk = GetGithubCredentials(cache.Entity.Credentials.GetID()) + creds, ok = GetGithubCredentials(cache.Entity.Credentials.ID) case params.GiteaEndpointType: - // add gitea credentials getter - return cache.Entity, false + creds, ok = GetGiteaCredentials(cache.Entity.Credentials.ID) } - if credsOk { - cache.Entity.Credentials = forgeCredsGetter.GetForgeCredentials() + if ok { + cache.Entity.Credentials = creds } return cache.Entity, true } @@ -254,17 +252,16 @@ func (e *EntityCache) GetAllEntities() []params.ForgeEntity { var entities []params.ForgeEntity for _, cache := range e.entities { // Get the credentials from the credentials cache. - var forgeCredsGetter params.ForgeCredentialsGetter - var credsOk bool + var creds params.ForgeCredentials + var ok bool switch cache.Entity.Credentials.ForgeType { case params.GithubEndpointType: - forgeCredsGetter, credsOk = GetGithubCredentials(cache.Entity.Credentials.GetID()) + creds, ok = GetGithubCredentials(cache.Entity.Credentials.ID) case params.GiteaEndpointType: - // add gitea credentials getter - return nil + creds, ok = GetGiteaCredentials(cache.Entity.Credentials.ID) } - if credsOk { - cache.Entity.Credentials = forgeCredsGetter.GetForgeCredentials() + if ok { + cache.Entity.Credentials = creds } entities = append(entities, cache.Entity) } diff --git a/cache/tools_cache.go b/cache/tools_cache.go index f4a2db62..0698c41e 100644 --- a/cache/tools_cache.go +++ b/cache/tools_cache.go @@ -19,6 +19,7 @@ func init() { type GithubEntityTools struct { updatedAt time.Time + expiresAt time.Time entity params.ForgeEntity tools []commonParams.RunnerApplicationDownload } @@ -34,10 +35,12 @@ func (g *GithubToolsCache) Get(entityID string) ([]commonParams.RunnerApplicatio defer g.mux.Unlock() if cache, ok := g.entities[entityID]; ok { - if time.Since(cache.updatedAt) > 1*time.Hour { - // Stale cache, remove it. - delete(g.entities, entityID) - return nil, false + if cache.entity.Credentials.ForgeType == params.GithubEndpointType { + if time.Now().UTC().After(cache.expiresAt.Add(-5 * time.Minute)) { + // Stale cache, remove it. + delete(g.entities, entityID) + return nil, false + } } return cache.tools, true } @@ -48,11 +51,17 @@ func (g *GithubToolsCache) Set(entity params.ForgeEntity, tools []commonParams.R g.mux.Lock() defer g.mux.Unlock() - g.entities[entity.ID] = GithubEntityTools{ + forgeTools := GithubEntityTools{ updatedAt: time.Now(), entity: entity, tools: tools, } + + if entity.Credentials.ForgeType == params.GithubEndpointType { + forgeTools.expiresAt = time.Now().Add(24 * time.Hour) + } + + g.entities[entity.ID] = forgeTools } func SetGithubToolsCache(entity params.ForgeEntity, tools []commonParams.RunnerApplicationDownload) { diff --git a/client/credentials/create_credentials_responses.go b/client/credentials/create_credentials_responses.go index cc5dc5dc..a0037edf 100644 --- a/client/credentials/create_credentials_responses.go +++ b/client/credentials/create_credentials_responses.go @@ -50,10 +50,10 @@ func NewCreateCredentialsOK() *CreateCredentialsOK { /* CreateCredentialsOK describes a response with status code 200, with default header values. -GithubCredentials +ForgeCredentials */ type CreateCredentialsOK struct { - Payload garm_params.GithubCredentials + Payload garm_params.ForgeCredentials } // IsSuccess returns true when this create credentials o k response has a 2xx status code @@ -96,7 +96,7 @@ func (o *CreateCredentialsOK) String() string { return fmt.Sprintf("[POST /github/credentials][%d] createCredentialsOK %s", 200, payload) } -func (o *CreateCredentialsOK) GetPayload() garm_params.GithubCredentials { +func (o *CreateCredentialsOK) GetPayload() garm_params.ForgeCredentials { return o.Payload } diff --git a/client/credentials/create_gitea_credentials_parameters.go b/client/credentials/create_gitea_credentials_parameters.go new file mode 100644 index 00000000..6e255bfa --- /dev/null +++ b/client/credentials/create_gitea_credentials_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credentials + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + garm_params "github.com/cloudbase/garm/params" +) + +// NewCreateGiteaCredentialsParams creates a new CreateGiteaCredentialsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateGiteaCredentialsParams() *CreateGiteaCredentialsParams { + return &CreateGiteaCredentialsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateGiteaCredentialsParamsWithTimeout creates a new CreateGiteaCredentialsParams object +// with the ability to set a timeout on a request. +func NewCreateGiteaCredentialsParamsWithTimeout(timeout time.Duration) *CreateGiteaCredentialsParams { + return &CreateGiteaCredentialsParams{ + timeout: timeout, + } +} + +// NewCreateGiteaCredentialsParamsWithContext creates a new CreateGiteaCredentialsParams object +// with the ability to set a context for a request. +func NewCreateGiteaCredentialsParamsWithContext(ctx context.Context) *CreateGiteaCredentialsParams { + return &CreateGiteaCredentialsParams{ + Context: ctx, + } +} + +// NewCreateGiteaCredentialsParamsWithHTTPClient creates a new CreateGiteaCredentialsParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateGiteaCredentialsParamsWithHTTPClient(client *http.Client) *CreateGiteaCredentialsParams { + return &CreateGiteaCredentialsParams{ + HTTPClient: client, + } +} + +/* +CreateGiteaCredentialsParams contains all the parameters to send to the API endpoint + + for the create gitea credentials operation. + + Typically these are written to a http.Request. +*/ +type CreateGiteaCredentialsParams struct { + + /* Body. + + Parameters used when creating a Gitea credential. + */ + Body garm_params.CreateGiteaCredentialsParams + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create gitea credentials params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateGiteaCredentialsParams) WithDefaults() *CreateGiteaCredentialsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create gitea credentials params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateGiteaCredentialsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create gitea credentials params +func (o *CreateGiteaCredentialsParams) WithTimeout(timeout time.Duration) *CreateGiteaCredentialsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create gitea credentials params +func (o *CreateGiteaCredentialsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create gitea credentials params +func (o *CreateGiteaCredentialsParams) WithContext(ctx context.Context) *CreateGiteaCredentialsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create gitea credentials params +func (o *CreateGiteaCredentialsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create gitea credentials params +func (o *CreateGiteaCredentialsParams) WithHTTPClient(client *http.Client) *CreateGiteaCredentialsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create gitea credentials params +func (o *CreateGiteaCredentialsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create gitea credentials params +func (o *CreateGiteaCredentialsParams) WithBody(body garm_params.CreateGiteaCredentialsParams) *CreateGiteaCredentialsParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create gitea credentials params +func (o *CreateGiteaCredentialsParams) SetBody(body garm_params.CreateGiteaCredentialsParams) { + o.Body = body +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateGiteaCredentialsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/credentials/create_gitea_credentials_responses.go b/client/credentials/create_gitea_credentials_responses.go new file mode 100644 index 00000000..2389cb04 --- /dev/null +++ b/client/credentials/create_gitea_credentials_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credentials + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + apiserver_params "github.com/cloudbase/garm/apiserver/params" + garm_params "github.com/cloudbase/garm/params" +) + +// CreateGiteaCredentialsReader is a Reader for the CreateGiteaCredentials structure. +type CreateGiteaCredentialsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateGiteaCredentialsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateGiteaCredentialsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewCreateGiteaCredentialsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /gitea/credentials] CreateGiteaCredentials", response, response.Code()) + } +} + +// NewCreateGiteaCredentialsOK creates a CreateGiteaCredentialsOK with default headers values +func NewCreateGiteaCredentialsOK() *CreateGiteaCredentialsOK { + return &CreateGiteaCredentialsOK{} +} + +/* +CreateGiteaCredentialsOK describes a response with status code 200, with default header values. + +ForgeCredentials +*/ +type CreateGiteaCredentialsOK struct { + Payload garm_params.ForgeCredentials +} + +// IsSuccess returns true when this create gitea credentials o k response has a 2xx status code +func (o *CreateGiteaCredentialsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create gitea credentials o k response has a 3xx status code +func (o *CreateGiteaCredentialsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create gitea credentials o k response has a 4xx status code +func (o *CreateGiteaCredentialsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create gitea credentials o k response has a 5xx status code +func (o *CreateGiteaCredentialsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create gitea credentials o k response a status code equal to that given +func (o *CreateGiteaCredentialsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the create gitea credentials o k response +func (o *CreateGiteaCredentialsOK) Code() int { + return 200 +} + +func (o *CreateGiteaCredentialsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /gitea/credentials][%d] createGiteaCredentialsOK %s", 200, payload) +} + +func (o *CreateGiteaCredentialsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /gitea/credentials][%d] createGiteaCredentialsOK %s", 200, payload) +} + +func (o *CreateGiteaCredentialsOK) GetPayload() garm_params.ForgeCredentials { + return o.Payload +} + +func (o *CreateGiteaCredentialsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateGiteaCredentialsBadRequest creates a CreateGiteaCredentialsBadRequest with default headers values +func NewCreateGiteaCredentialsBadRequest() *CreateGiteaCredentialsBadRequest { + return &CreateGiteaCredentialsBadRequest{} +} + +/* +CreateGiteaCredentialsBadRequest describes a response with status code 400, with default header values. + +APIErrorResponse +*/ +type CreateGiteaCredentialsBadRequest struct { + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this create gitea credentials bad request response has a 2xx status code +func (o *CreateGiteaCredentialsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this create gitea credentials bad request response has a 3xx status code +func (o *CreateGiteaCredentialsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create gitea credentials bad request response has a 4xx status code +func (o *CreateGiteaCredentialsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this create gitea credentials bad request response has a 5xx status code +func (o *CreateGiteaCredentialsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this create gitea credentials bad request response a status code equal to that given +func (o *CreateGiteaCredentialsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the create gitea credentials bad request response +func (o *CreateGiteaCredentialsBadRequest) Code() int { + return 400 +} + +func (o *CreateGiteaCredentialsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /gitea/credentials][%d] createGiteaCredentialsBadRequest %s", 400, payload) +} + +func (o *CreateGiteaCredentialsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /gitea/credentials][%d] createGiteaCredentialsBadRequest %s", 400, payload) +} + +func (o *CreateGiteaCredentialsBadRequest) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *CreateGiteaCredentialsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/credentials/credentials_client.go b/client/credentials/credentials_client.go index 9d7b0563..3dfe1abd 100644 --- a/client/credentials/credentials_client.go +++ b/client/credentials/credentials_client.go @@ -58,14 +58,24 @@ type ClientOption func(*runtime.ClientOperation) type ClientService interface { CreateCredentials(params *CreateCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateCredentialsOK, error) + CreateGiteaCredentials(params *CreateGiteaCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateGiteaCredentialsOK, error) + DeleteCredentials(params *DeleteCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error + DeleteGiteaCredentials(params *DeleteGiteaCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error + GetCredentials(params *GetCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCredentialsOK, error) + GetGiteaCredentials(params *GetGiteaCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetGiteaCredentialsOK, error) + ListCredentials(params *ListCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListCredentialsOK, error) + ListGiteaCredentials(params *ListGiteaCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListGiteaCredentialsOK, error) + UpdateCredentials(params *UpdateCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateCredentialsOK, error) + UpdateGiteaCredentials(params *UpdateGiteaCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateGiteaCredentialsOK, error) + SetTransport(transport runtime.ClientTransport) } @@ -108,6 +118,45 @@ func (a *Client) CreateCredentials(params *CreateCredentialsParams, authInfo run panic(msg) } +/* +CreateGiteaCredentials creates a gitea credential +*/ +func (a *Client) CreateGiteaCredentials(params *CreateGiteaCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateGiteaCredentialsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateGiteaCredentialsParams() + } + op := &runtime.ClientOperation{ + ID: "CreateGiteaCredentials", + Method: "POST", + PathPattern: "/gitea/credentials", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateGiteaCredentialsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateGiteaCredentialsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for CreateGiteaCredentials: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + /* DeleteCredentials deletes a git hub credential */ @@ -140,6 +189,38 @@ func (a *Client) DeleteCredentials(params *DeleteCredentialsParams, authInfo run return nil } +/* +DeleteGiteaCredentials deletes a gitea credential +*/ +func (a *Client) DeleteGiteaCredentials(params *DeleteGiteaCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteGiteaCredentialsParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteGiteaCredentials", + Method: "DELETE", + PathPattern: "/gitea/credentials/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteGiteaCredentialsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + _, err := a.transport.Submit(op) + if err != nil { + return err + } + return nil +} + /* GetCredentials gets a git hub credential */ @@ -179,6 +260,45 @@ func (a *Client) GetCredentials(params *GetCredentialsParams, authInfo runtime.C panic(msg) } +/* +GetGiteaCredentials gets a gitea credential +*/ +func (a *Client) GetGiteaCredentials(params *GetGiteaCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetGiteaCredentialsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetGiteaCredentialsParams() + } + op := &runtime.ClientOperation{ + ID: "GetGiteaCredentials", + Method: "GET", + PathPattern: "/gitea/credentials/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetGiteaCredentialsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetGiteaCredentialsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetGiteaCredentials: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + /* ListCredentials lists all credentials */ @@ -218,6 +338,45 @@ func (a *Client) ListCredentials(params *ListCredentialsParams, authInfo runtime panic(msg) } +/* +ListGiteaCredentials lists all credentials +*/ +func (a *Client) ListGiteaCredentials(params *ListGiteaCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListGiteaCredentialsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewListGiteaCredentialsParams() + } + op := &runtime.ClientOperation{ + ID: "ListGiteaCredentials", + Method: "GET", + PathPattern: "/gitea/credentials", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ListGiteaCredentialsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ListGiteaCredentialsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for ListGiteaCredentials: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + /* UpdateCredentials updates a git hub credential */ @@ -257,6 +416,45 @@ func (a *Client) UpdateCredentials(params *UpdateCredentialsParams, authInfo run panic(msg) } +/* +UpdateGiteaCredentials updates a gitea credential +*/ +func (a *Client) UpdateGiteaCredentials(params *UpdateGiteaCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateGiteaCredentialsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewUpdateGiteaCredentialsParams() + } + op := &runtime.ClientOperation{ + ID: "UpdateGiteaCredentials", + Method: "PUT", + PathPattern: "/gitea/credentials/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &UpdateGiteaCredentialsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*UpdateGiteaCredentialsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for UpdateGiteaCredentials: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + // SetTransport changes the transport on the client func (a *Client) SetTransport(transport runtime.ClientTransport) { a.transport = transport diff --git a/client/credentials/delete_gitea_credentials_parameters.go b/client/credentials/delete_gitea_credentials_parameters.go new file mode 100644 index 00000000..598ac477 --- /dev/null +++ b/client/credentials/delete_gitea_credentials_parameters.go @@ -0,0 +1,152 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credentials + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDeleteGiteaCredentialsParams creates a new DeleteGiteaCredentialsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteGiteaCredentialsParams() *DeleteGiteaCredentialsParams { + return &DeleteGiteaCredentialsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteGiteaCredentialsParamsWithTimeout creates a new DeleteGiteaCredentialsParams object +// with the ability to set a timeout on a request. +func NewDeleteGiteaCredentialsParamsWithTimeout(timeout time.Duration) *DeleteGiteaCredentialsParams { + return &DeleteGiteaCredentialsParams{ + timeout: timeout, + } +} + +// NewDeleteGiteaCredentialsParamsWithContext creates a new DeleteGiteaCredentialsParams object +// with the ability to set a context for a request. +func NewDeleteGiteaCredentialsParamsWithContext(ctx context.Context) *DeleteGiteaCredentialsParams { + return &DeleteGiteaCredentialsParams{ + Context: ctx, + } +} + +// NewDeleteGiteaCredentialsParamsWithHTTPClient creates a new DeleteGiteaCredentialsParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteGiteaCredentialsParamsWithHTTPClient(client *http.Client) *DeleteGiteaCredentialsParams { + return &DeleteGiteaCredentialsParams{ + HTTPClient: client, + } +} + +/* +DeleteGiteaCredentialsParams contains all the parameters to send to the API endpoint + + for the delete gitea credentials operation. + + Typically these are written to a http.Request. +*/ +type DeleteGiteaCredentialsParams struct { + + /* ID. + + ID of the Gitea credential. + */ + ID int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete gitea credentials params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteGiteaCredentialsParams) WithDefaults() *DeleteGiteaCredentialsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete gitea credentials params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteGiteaCredentialsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete gitea credentials params +func (o *DeleteGiteaCredentialsParams) WithTimeout(timeout time.Duration) *DeleteGiteaCredentialsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete gitea credentials params +func (o *DeleteGiteaCredentialsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete gitea credentials params +func (o *DeleteGiteaCredentialsParams) WithContext(ctx context.Context) *DeleteGiteaCredentialsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete gitea credentials params +func (o *DeleteGiteaCredentialsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete gitea credentials params +func (o *DeleteGiteaCredentialsParams) WithHTTPClient(client *http.Client) *DeleteGiteaCredentialsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete gitea credentials params +func (o *DeleteGiteaCredentialsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the delete gitea credentials params +func (o *DeleteGiteaCredentialsParams) WithID(id int64) *DeleteGiteaCredentialsParams { + o.SetID(id) + return o +} + +// SetID adds the id to the delete gitea credentials params +func (o *DeleteGiteaCredentialsParams) SetID(id int64) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteGiteaCredentialsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", swag.FormatInt64(o.ID)); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/credentials/delete_gitea_credentials_responses.go b/client/credentials/delete_gitea_credentials_responses.go new file mode 100644 index 00000000..d1df7b0b --- /dev/null +++ b/client/credentials/delete_gitea_credentials_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credentials + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + apiserver_params "github.com/cloudbase/garm/apiserver/params" +) + +// DeleteGiteaCredentialsReader is a Reader for the DeleteGiteaCredentials structure. +type DeleteGiteaCredentialsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteGiteaCredentialsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + result := NewDeleteGiteaCredentialsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result +} + +// NewDeleteGiteaCredentialsDefault creates a DeleteGiteaCredentialsDefault with default headers values +func NewDeleteGiteaCredentialsDefault(code int) *DeleteGiteaCredentialsDefault { + return &DeleteGiteaCredentialsDefault{ + _statusCode: code, + } +} + +/* +DeleteGiteaCredentialsDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type DeleteGiteaCredentialsDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this delete gitea credentials default response has a 2xx status code +func (o *DeleteGiteaCredentialsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete gitea credentials default response has a 3xx status code +func (o *DeleteGiteaCredentialsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete gitea credentials default response has a 4xx status code +func (o *DeleteGiteaCredentialsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete gitea credentials default response has a 5xx status code +func (o *DeleteGiteaCredentialsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete gitea credentials default response a status code equal to that given +func (o *DeleteGiteaCredentialsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the delete gitea credentials default response +func (o *DeleteGiteaCredentialsDefault) Code() int { + return o._statusCode +} + +func (o *DeleteGiteaCredentialsDefault) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /gitea/credentials/{id}][%d] DeleteGiteaCredentials default %s", o._statusCode, payload) +} + +func (o *DeleteGiteaCredentialsDefault) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /gitea/credentials/{id}][%d] DeleteGiteaCredentials default %s", o._statusCode, payload) +} + +func (o *DeleteGiteaCredentialsDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *DeleteGiteaCredentialsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/credentials/get_credentials_responses.go b/client/credentials/get_credentials_responses.go index 1c2b800b..4538c16e 100644 --- a/client/credentials/get_credentials_responses.go +++ b/client/credentials/get_credentials_responses.go @@ -50,10 +50,10 @@ func NewGetCredentialsOK() *GetCredentialsOK { /* GetCredentialsOK describes a response with status code 200, with default header values. -GithubCredentials +ForgeCredentials */ type GetCredentialsOK struct { - Payload garm_params.GithubCredentials + Payload garm_params.ForgeCredentials } // IsSuccess returns true when this get credentials o k response has a 2xx status code @@ -96,7 +96,7 @@ func (o *GetCredentialsOK) String() string { return fmt.Sprintf("[GET /github/credentials/{id}][%d] getCredentialsOK %s", 200, payload) } -func (o *GetCredentialsOK) GetPayload() garm_params.GithubCredentials { +func (o *GetCredentialsOK) GetPayload() garm_params.ForgeCredentials { return o.Payload } diff --git a/client/credentials/get_gitea_credentials_parameters.go b/client/credentials/get_gitea_credentials_parameters.go new file mode 100644 index 00000000..a844c326 --- /dev/null +++ b/client/credentials/get_gitea_credentials_parameters.go @@ -0,0 +1,152 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credentials + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetGiteaCredentialsParams creates a new GetGiteaCredentialsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetGiteaCredentialsParams() *GetGiteaCredentialsParams { + return &GetGiteaCredentialsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetGiteaCredentialsParamsWithTimeout creates a new GetGiteaCredentialsParams object +// with the ability to set a timeout on a request. +func NewGetGiteaCredentialsParamsWithTimeout(timeout time.Duration) *GetGiteaCredentialsParams { + return &GetGiteaCredentialsParams{ + timeout: timeout, + } +} + +// NewGetGiteaCredentialsParamsWithContext creates a new GetGiteaCredentialsParams object +// with the ability to set a context for a request. +func NewGetGiteaCredentialsParamsWithContext(ctx context.Context) *GetGiteaCredentialsParams { + return &GetGiteaCredentialsParams{ + Context: ctx, + } +} + +// NewGetGiteaCredentialsParamsWithHTTPClient creates a new GetGiteaCredentialsParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetGiteaCredentialsParamsWithHTTPClient(client *http.Client) *GetGiteaCredentialsParams { + return &GetGiteaCredentialsParams{ + HTTPClient: client, + } +} + +/* +GetGiteaCredentialsParams contains all the parameters to send to the API endpoint + + for the get gitea credentials operation. + + Typically these are written to a http.Request. +*/ +type GetGiteaCredentialsParams struct { + + /* ID. + + ID of the Gitea credential. + */ + ID int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get gitea credentials params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetGiteaCredentialsParams) WithDefaults() *GetGiteaCredentialsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get gitea credentials params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetGiteaCredentialsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get gitea credentials params +func (o *GetGiteaCredentialsParams) WithTimeout(timeout time.Duration) *GetGiteaCredentialsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get gitea credentials params +func (o *GetGiteaCredentialsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get gitea credentials params +func (o *GetGiteaCredentialsParams) WithContext(ctx context.Context) *GetGiteaCredentialsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get gitea credentials params +func (o *GetGiteaCredentialsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get gitea credentials params +func (o *GetGiteaCredentialsParams) WithHTTPClient(client *http.Client) *GetGiteaCredentialsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get gitea credentials params +func (o *GetGiteaCredentialsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get gitea credentials params +func (o *GetGiteaCredentialsParams) WithID(id int64) *GetGiteaCredentialsParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get gitea credentials params +func (o *GetGiteaCredentialsParams) SetID(id int64) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetGiteaCredentialsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", swag.FormatInt64(o.ID)); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/credentials/get_gitea_credentials_responses.go b/client/credentials/get_gitea_credentials_responses.go new file mode 100644 index 00000000..ba116d63 --- /dev/null +++ b/client/credentials/get_gitea_credentials_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credentials + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + apiserver_params "github.com/cloudbase/garm/apiserver/params" + garm_params "github.com/cloudbase/garm/params" +) + +// GetGiteaCredentialsReader is a Reader for the GetGiteaCredentials structure. +type GetGiteaCredentialsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetGiteaCredentialsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetGiteaCredentialsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetGiteaCredentialsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /gitea/credentials/{id}] GetGiteaCredentials", response, response.Code()) + } +} + +// NewGetGiteaCredentialsOK creates a GetGiteaCredentialsOK with default headers values +func NewGetGiteaCredentialsOK() *GetGiteaCredentialsOK { + return &GetGiteaCredentialsOK{} +} + +/* +GetGiteaCredentialsOK describes a response with status code 200, with default header values. + +ForgeCredentials +*/ +type GetGiteaCredentialsOK struct { + Payload garm_params.ForgeCredentials +} + +// IsSuccess returns true when this get gitea credentials o k response has a 2xx status code +func (o *GetGiteaCredentialsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get gitea credentials o k response has a 3xx status code +func (o *GetGiteaCredentialsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get gitea credentials o k response has a 4xx status code +func (o *GetGiteaCredentialsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get gitea credentials o k response has a 5xx status code +func (o *GetGiteaCredentialsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get gitea credentials o k response a status code equal to that given +func (o *GetGiteaCredentialsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get gitea credentials o k response +func (o *GetGiteaCredentialsOK) Code() int { + return 200 +} + +func (o *GetGiteaCredentialsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /gitea/credentials/{id}][%d] getGiteaCredentialsOK %s", 200, payload) +} + +func (o *GetGiteaCredentialsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /gitea/credentials/{id}][%d] getGiteaCredentialsOK %s", 200, payload) +} + +func (o *GetGiteaCredentialsOK) GetPayload() garm_params.ForgeCredentials { + return o.Payload +} + +func (o *GetGiteaCredentialsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetGiteaCredentialsBadRequest creates a GetGiteaCredentialsBadRequest with default headers values +func NewGetGiteaCredentialsBadRequest() *GetGiteaCredentialsBadRequest { + return &GetGiteaCredentialsBadRequest{} +} + +/* +GetGiteaCredentialsBadRequest describes a response with status code 400, with default header values. + +APIErrorResponse +*/ +type GetGiteaCredentialsBadRequest struct { + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this get gitea credentials bad request response has a 2xx status code +func (o *GetGiteaCredentialsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get gitea credentials bad request response has a 3xx status code +func (o *GetGiteaCredentialsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get gitea credentials bad request response has a 4xx status code +func (o *GetGiteaCredentialsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get gitea credentials bad request response has a 5xx status code +func (o *GetGiteaCredentialsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get gitea credentials bad request response a status code equal to that given +func (o *GetGiteaCredentialsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get gitea credentials bad request response +func (o *GetGiteaCredentialsBadRequest) Code() int { + return 400 +} + +func (o *GetGiteaCredentialsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /gitea/credentials/{id}][%d] getGiteaCredentialsBadRequest %s", 400, payload) +} + +func (o *GetGiteaCredentialsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /gitea/credentials/{id}][%d] getGiteaCredentialsBadRequest %s", 400, payload) +} + +func (o *GetGiteaCredentialsBadRequest) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *GetGiteaCredentialsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/credentials/list_gitea_credentials_parameters.go b/client/credentials/list_gitea_credentials_parameters.go new file mode 100644 index 00000000..5e321a88 --- /dev/null +++ b/client/credentials/list_gitea_credentials_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credentials + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewListGiteaCredentialsParams creates a new ListGiteaCredentialsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewListGiteaCredentialsParams() *ListGiteaCredentialsParams { + return &ListGiteaCredentialsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewListGiteaCredentialsParamsWithTimeout creates a new ListGiteaCredentialsParams object +// with the ability to set a timeout on a request. +func NewListGiteaCredentialsParamsWithTimeout(timeout time.Duration) *ListGiteaCredentialsParams { + return &ListGiteaCredentialsParams{ + timeout: timeout, + } +} + +// NewListGiteaCredentialsParamsWithContext creates a new ListGiteaCredentialsParams object +// with the ability to set a context for a request. +func NewListGiteaCredentialsParamsWithContext(ctx context.Context) *ListGiteaCredentialsParams { + return &ListGiteaCredentialsParams{ + Context: ctx, + } +} + +// NewListGiteaCredentialsParamsWithHTTPClient creates a new ListGiteaCredentialsParams object +// with the ability to set a custom HTTPClient for a request. +func NewListGiteaCredentialsParamsWithHTTPClient(client *http.Client) *ListGiteaCredentialsParams { + return &ListGiteaCredentialsParams{ + HTTPClient: client, + } +} + +/* +ListGiteaCredentialsParams contains all the parameters to send to the API endpoint + + for the list gitea credentials operation. + + Typically these are written to a http.Request. +*/ +type ListGiteaCredentialsParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the list gitea credentials params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListGiteaCredentialsParams) WithDefaults() *ListGiteaCredentialsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the list gitea credentials params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListGiteaCredentialsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the list gitea credentials params +func (o *ListGiteaCredentialsParams) WithTimeout(timeout time.Duration) *ListGiteaCredentialsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list gitea credentials params +func (o *ListGiteaCredentialsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list gitea credentials params +func (o *ListGiteaCredentialsParams) WithContext(ctx context.Context) *ListGiteaCredentialsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list gitea credentials params +func (o *ListGiteaCredentialsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list gitea credentials params +func (o *ListGiteaCredentialsParams) WithHTTPClient(client *http.Client) *ListGiteaCredentialsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list gitea credentials params +func (o *ListGiteaCredentialsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListGiteaCredentialsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/credentials/list_gitea_credentials_responses.go b/client/credentials/list_gitea_credentials_responses.go new file mode 100644 index 00000000..f27864be --- /dev/null +++ b/client/credentials/list_gitea_credentials_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credentials + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + apiserver_params "github.com/cloudbase/garm/apiserver/params" + garm_params "github.com/cloudbase/garm/params" +) + +// ListGiteaCredentialsReader is a Reader for the ListGiteaCredentials structure. +type ListGiteaCredentialsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListGiteaCredentialsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListGiteaCredentialsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewListGiteaCredentialsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /gitea/credentials] ListGiteaCredentials", response, response.Code()) + } +} + +// NewListGiteaCredentialsOK creates a ListGiteaCredentialsOK with default headers values +func NewListGiteaCredentialsOK() *ListGiteaCredentialsOK { + return &ListGiteaCredentialsOK{} +} + +/* +ListGiteaCredentialsOK describes a response with status code 200, with default header values. + +Credentials +*/ +type ListGiteaCredentialsOK struct { + Payload garm_params.Credentials +} + +// IsSuccess returns true when this list gitea credentials o k response has a 2xx status code +func (o *ListGiteaCredentialsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this list gitea credentials o k response has a 3xx status code +func (o *ListGiteaCredentialsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list gitea credentials o k response has a 4xx status code +func (o *ListGiteaCredentialsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this list gitea credentials o k response has a 5xx status code +func (o *ListGiteaCredentialsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this list gitea credentials o k response a status code equal to that given +func (o *ListGiteaCredentialsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the list gitea credentials o k response +func (o *ListGiteaCredentialsOK) Code() int { + return 200 +} + +func (o *ListGiteaCredentialsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /gitea/credentials][%d] listGiteaCredentialsOK %s", 200, payload) +} + +func (o *ListGiteaCredentialsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /gitea/credentials][%d] listGiteaCredentialsOK %s", 200, payload) +} + +func (o *ListGiteaCredentialsOK) GetPayload() garm_params.Credentials { + return o.Payload +} + +func (o *ListGiteaCredentialsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewListGiteaCredentialsBadRequest creates a ListGiteaCredentialsBadRequest with default headers values +func NewListGiteaCredentialsBadRequest() *ListGiteaCredentialsBadRequest { + return &ListGiteaCredentialsBadRequest{} +} + +/* +ListGiteaCredentialsBadRequest describes a response with status code 400, with default header values. + +APIErrorResponse +*/ +type ListGiteaCredentialsBadRequest struct { + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this list gitea credentials bad request response has a 2xx status code +func (o *ListGiteaCredentialsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this list gitea credentials bad request response has a 3xx status code +func (o *ListGiteaCredentialsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list gitea credentials bad request response has a 4xx status code +func (o *ListGiteaCredentialsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this list gitea credentials bad request response has a 5xx status code +func (o *ListGiteaCredentialsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this list gitea credentials bad request response a status code equal to that given +func (o *ListGiteaCredentialsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the list gitea credentials bad request response +func (o *ListGiteaCredentialsBadRequest) Code() int { + return 400 +} + +func (o *ListGiteaCredentialsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /gitea/credentials][%d] listGiteaCredentialsBadRequest %s", 400, payload) +} + +func (o *ListGiteaCredentialsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /gitea/credentials][%d] listGiteaCredentialsBadRequest %s", 400, payload) +} + +func (o *ListGiteaCredentialsBadRequest) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *ListGiteaCredentialsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/credentials/update_credentials_responses.go b/client/credentials/update_credentials_responses.go index b0254604..6a9f37f8 100644 --- a/client/credentials/update_credentials_responses.go +++ b/client/credentials/update_credentials_responses.go @@ -50,10 +50,10 @@ func NewUpdateCredentialsOK() *UpdateCredentialsOK { /* UpdateCredentialsOK describes a response with status code 200, with default header values. -GithubCredentials +ForgeCredentials */ type UpdateCredentialsOK struct { - Payload garm_params.GithubCredentials + Payload garm_params.ForgeCredentials } // IsSuccess returns true when this update credentials o k response has a 2xx status code @@ -96,7 +96,7 @@ func (o *UpdateCredentialsOK) String() string { return fmt.Sprintf("[PUT /github/credentials/{id}][%d] updateCredentialsOK %s", 200, payload) } -func (o *UpdateCredentialsOK) GetPayload() garm_params.GithubCredentials { +func (o *UpdateCredentialsOK) GetPayload() garm_params.ForgeCredentials { return o.Payload } diff --git a/client/credentials/update_gitea_credentials_parameters.go b/client/credentials/update_gitea_credentials_parameters.go new file mode 100644 index 00000000..1907a0f2 --- /dev/null +++ b/client/credentials/update_gitea_credentials_parameters.go @@ -0,0 +1,174 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credentials + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + garm_params "github.com/cloudbase/garm/params" +) + +// NewUpdateGiteaCredentialsParams creates a new UpdateGiteaCredentialsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewUpdateGiteaCredentialsParams() *UpdateGiteaCredentialsParams { + return &UpdateGiteaCredentialsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewUpdateGiteaCredentialsParamsWithTimeout creates a new UpdateGiteaCredentialsParams object +// with the ability to set a timeout on a request. +func NewUpdateGiteaCredentialsParamsWithTimeout(timeout time.Duration) *UpdateGiteaCredentialsParams { + return &UpdateGiteaCredentialsParams{ + timeout: timeout, + } +} + +// NewUpdateGiteaCredentialsParamsWithContext creates a new UpdateGiteaCredentialsParams object +// with the ability to set a context for a request. +func NewUpdateGiteaCredentialsParamsWithContext(ctx context.Context) *UpdateGiteaCredentialsParams { + return &UpdateGiteaCredentialsParams{ + Context: ctx, + } +} + +// NewUpdateGiteaCredentialsParamsWithHTTPClient creates a new UpdateGiteaCredentialsParams object +// with the ability to set a custom HTTPClient for a request. +func NewUpdateGiteaCredentialsParamsWithHTTPClient(client *http.Client) *UpdateGiteaCredentialsParams { + return &UpdateGiteaCredentialsParams{ + HTTPClient: client, + } +} + +/* +UpdateGiteaCredentialsParams contains all the parameters to send to the API endpoint + + for the update gitea credentials operation. + + Typically these are written to a http.Request. +*/ +type UpdateGiteaCredentialsParams struct { + + /* Body. + + Parameters used when updating a Gitea credential. + */ + Body garm_params.UpdateGiteaCredentialsParams + + /* ID. + + ID of the Gitea credential. + */ + ID int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the update gitea credentials params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UpdateGiteaCredentialsParams) WithDefaults() *UpdateGiteaCredentialsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the update gitea credentials params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UpdateGiteaCredentialsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the update gitea credentials params +func (o *UpdateGiteaCredentialsParams) WithTimeout(timeout time.Duration) *UpdateGiteaCredentialsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the update gitea credentials params +func (o *UpdateGiteaCredentialsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the update gitea credentials params +func (o *UpdateGiteaCredentialsParams) WithContext(ctx context.Context) *UpdateGiteaCredentialsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the update gitea credentials params +func (o *UpdateGiteaCredentialsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the update gitea credentials params +func (o *UpdateGiteaCredentialsParams) WithHTTPClient(client *http.Client) *UpdateGiteaCredentialsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the update gitea credentials params +func (o *UpdateGiteaCredentialsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the update gitea credentials params +func (o *UpdateGiteaCredentialsParams) WithBody(body garm_params.UpdateGiteaCredentialsParams) *UpdateGiteaCredentialsParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the update gitea credentials params +func (o *UpdateGiteaCredentialsParams) SetBody(body garm_params.UpdateGiteaCredentialsParams) { + o.Body = body +} + +// WithID adds the id to the update gitea credentials params +func (o *UpdateGiteaCredentialsParams) WithID(id int64) *UpdateGiteaCredentialsParams { + o.SetID(id) + return o +} + +// SetID adds the id to the update gitea credentials params +func (o *UpdateGiteaCredentialsParams) SetID(id int64) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *UpdateGiteaCredentialsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + + // path param id + if err := r.SetPathParam("id", swag.FormatInt64(o.ID)); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/credentials/update_gitea_credentials_responses.go b/client/credentials/update_gitea_credentials_responses.go new file mode 100644 index 00000000..edbb54d8 --- /dev/null +++ b/client/credentials/update_gitea_credentials_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credentials + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + apiserver_params "github.com/cloudbase/garm/apiserver/params" + garm_params "github.com/cloudbase/garm/params" +) + +// UpdateGiteaCredentialsReader is a Reader for the UpdateGiteaCredentials structure. +type UpdateGiteaCredentialsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UpdateGiteaCredentialsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUpdateGiteaCredentialsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewUpdateGiteaCredentialsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[PUT /gitea/credentials/{id}] UpdateGiteaCredentials", response, response.Code()) + } +} + +// NewUpdateGiteaCredentialsOK creates a UpdateGiteaCredentialsOK with default headers values +func NewUpdateGiteaCredentialsOK() *UpdateGiteaCredentialsOK { + return &UpdateGiteaCredentialsOK{} +} + +/* +UpdateGiteaCredentialsOK describes a response with status code 200, with default header values. + +ForgeCredentials +*/ +type UpdateGiteaCredentialsOK struct { + Payload garm_params.ForgeCredentials +} + +// IsSuccess returns true when this update gitea credentials o k response has a 2xx status code +func (o *UpdateGiteaCredentialsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this update gitea credentials o k response has a 3xx status code +func (o *UpdateGiteaCredentialsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this update gitea credentials o k response has a 4xx status code +func (o *UpdateGiteaCredentialsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this update gitea credentials o k response has a 5xx status code +func (o *UpdateGiteaCredentialsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this update gitea credentials o k response a status code equal to that given +func (o *UpdateGiteaCredentialsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the update gitea credentials o k response +func (o *UpdateGiteaCredentialsOK) Code() int { + return 200 +} + +func (o *UpdateGiteaCredentialsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /gitea/credentials/{id}][%d] updateGiteaCredentialsOK %s", 200, payload) +} + +func (o *UpdateGiteaCredentialsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /gitea/credentials/{id}][%d] updateGiteaCredentialsOK %s", 200, payload) +} + +func (o *UpdateGiteaCredentialsOK) GetPayload() garm_params.ForgeCredentials { + return o.Payload +} + +func (o *UpdateGiteaCredentialsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdateGiteaCredentialsBadRequest creates a UpdateGiteaCredentialsBadRequest with default headers values +func NewUpdateGiteaCredentialsBadRequest() *UpdateGiteaCredentialsBadRequest { + return &UpdateGiteaCredentialsBadRequest{} +} + +/* +UpdateGiteaCredentialsBadRequest describes a response with status code 400, with default header values. + +APIErrorResponse +*/ +type UpdateGiteaCredentialsBadRequest struct { + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this update gitea credentials bad request response has a 2xx status code +func (o *UpdateGiteaCredentialsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this update gitea credentials bad request response has a 3xx status code +func (o *UpdateGiteaCredentialsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this update gitea credentials bad request response has a 4xx status code +func (o *UpdateGiteaCredentialsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this update gitea credentials bad request response has a 5xx status code +func (o *UpdateGiteaCredentialsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this update gitea credentials bad request response a status code equal to that given +func (o *UpdateGiteaCredentialsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the update gitea credentials bad request response +func (o *UpdateGiteaCredentialsBadRequest) Code() int { + return 400 +} + +func (o *UpdateGiteaCredentialsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /gitea/credentials/{id}][%d] updateGiteaCredentialsBadRequest %s", 400, payload) +} + +func (o *UpdateGiteaCredentialsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /gitea/credentials/{id}][%d] updateGiteaCredentialsBadRequest %s", 400, payload) +} + +func (o *UpdateGiteaCredentialsBadRequest) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *UpdateGiteaCredentialsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/endpoints/create_gitea_endpoint_parameters.go b/client/endpoints/create_gitea_endpoint_parameters.go new file mode 100644 index 00000000..11dfa73f --- /dev/null +++ b/client/endpoints/create_gitea_endpoint_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package endpoints + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + garm_params "github.com/cloudbase/garm/params" +) + +// NewCreateGiteaEndpointParams creates a new CreateGiteaEndpointParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewCreateGiteaEndpointParams() *CreateGiteaEndpointParams { + return &CreateGiteaEndpointParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateGiteaEndpointParamsWithTimeout creates a new CreateGiteaEndpointParams object +// with the ability to set a timeout on a request. +func NewCreateGiteaEndpointParamsWithTimeout(timeout time.Duration) *CreateGiteaEndpointParams { + return &CreateGiteaEndpointParams{ + timeout: timeout, + } +} + +// NewCreateGiteaEndpointParamsWithContext creates a new CreateGiteaEndpointParams object +// with the ability to set a context for a request. +func NewCreateGiteaEndpointParamsWithContext(ctx context.Context) *CreateGiteaEndpointParams { + return &CreateGiteaEndpointParams{ + Context: ctx, + } +} + +// NewCreateGiteaEndpointParamsWithHTTPClient creates a new CreateGiteaEndpointParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateGiteaEndpointParamsWithHTTPClient(client *http.Client) *CreateGiteaEndpointParams { + return &CreateGiteaEndpointParams{ + HTTPClient: client, + } +} + +/* +CreateGiteaEndpointParams contains all the parameters to send to the API endpoint + + for the create gitea endpoint operation. + + Typically these are written to a http.Request. +*/ +type CreateGiteaEndpointParams struct { + + /* Body. + + Parameters used when creating a Gitea endpoint. + */ + Body garm_params.CreateGiteaEndpointParams + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create gitea endpoint params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateGiteaEndpointParams) WithDefaults() *CreateGiteaEndpointParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create gitea endpoint params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateGiteaEndpointParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create gitea endpoint params +func (o *CreateGiteaEndpointParams) WithTimeout(timeout time.Duration) *CreateGiteaEndpointParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create gitea endpoint params +func (o *CreateGiteaEndpointParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create gitea endpoint params +func (o *CreateGiteaEndpointParams) WithContext(ctx context.Context) *CreateGiteaEndpointParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create gitea endpoint params +func (o *CreateGiteaEndpointParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create gitea endpoint params +func (o *CreateGiteaEndpointParams) WithHTTPClient(client *http.Client) *CreateGiteaEndpointParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create gitea endpoint params +func (o *CreateGiteaEndpointParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create gitea endpoint params +func (o *CreateGiteaEndpointParams) WithBody(body garm_params.CreateGiteaEndpointParams) *CreateGiteaEndpointParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create gitea endpoint params +func (o *CreateGiteaEndpointParams) SetBody(body garm_params.CreateGiteaEndpointParams) { + o.Body = body +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateGiteaEndpointParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/endpoints/create_gitea_endpoint_responses.go b/client/endpoints/create_gitea_endpoint_responses.go new file mode 100644 index 00000000..6e99a973 --- /dev/null +++ b/client/endpoints/create_gitea_endpoint_responses.go @@ -0,0 +1,184 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package endpoints + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + apiserver_params "github.com/cloudbase/garm/apiserver/params" + garm_params "github.com/cloudbase/garm/params" +) + +// CreateGiteaEndpointReader is a Reader for the CreateGiteaEndpoint structure. +type CreateGiteaEndpointReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateGiteaEndpointReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateGiteaEndpointOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateGiteaEndpointDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewCreateGiteaEndpointOK creates a CreateGiteaEndpointOK with default headers values +func NewCreateGiteaEndpointOK() *CreateGiteaEndpointOK { + return &CreateGiteaEndpointOK{} +} + +/* +CreateGiteaEndpointOK describes a response with status code 200, with default header values. + +ForgeEndpoint +*/ +type CreateGiteaEndpointOK struct { + Payload garm_params.ForgeEndpoint +} + +// IsSuccess returns true when this create gitea endpoint o k response has a 2xx status code +func (o *CreateGiteaEndpointOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create gitea endpoint o k response has a 3xx status code +func (o *CreateGiteaEndpointOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create gitea endpoint o k response has a 4xx status code +func (o *CreateGiteaEndpointOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create gitea endpoint o k response has a 5xx status code +func (o *CreateGiteaEndpointOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create gitea endpoint o k response a status code equal to that given +func (o *CreateGiteaEndpointOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the create gitea endpoint o k response +func (o *CreateGiteaEndpointOK) Code() int { + return 200 +} + +func (o *CreateGiteaEndpointOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /gitea/endpoints][%d] createGiteaEndpointOK %s", 200, payload) +} + +func (o *CreateGiteaEndpointOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /gitea/endpoints][%d] createGiteaEndpointOK %s", 200, payload) +} + +func (o *CreateGiteaEndpointOK) GetPayload() garm_params.ForgeEndpoint { + return o.Payload +} + +func (o *CreateGiteaEndpointOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateGiteaEndpointDefault creates a CreateGiteaEndpointDefault with default headers values +func NewCreateGiteaEndpointDefault(code int) *CreateGiteaEndpointDefault { + return &CreateGiteaEndpointDefault{ + _statusCode: code, + } +} + +/* +CreateGiteaEndpointDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type CreateGiteaEndpointDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this create gitea endpoint default response has a 2xx status code +func (o *CreateGiteaEndpointDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create gitea endpoint default response has a 3xx status code +func (o *CreateGiteaEndpointDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create gitea endpoint default response has a 4xx status code +func (o *CreateGiteaEndpointDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create gitea endpoint default response has a 5xx status code +func (o *CreateGiteaEndpointDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create gitea endpoint default response a status code equal to that given +func (o *CreateGiteaEndpointDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the create gitea endpoint default response +func (o *CreateGiteaEndpointDefault) Code() int { + return o._statusCode +} + +func (o *CreateGiteaEndpointDefault) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /gitea/endpoints][%d] CreateGiteaEndpoint default %s", o._statusCode, payload) +} + +func (o *CreateGiteaEndpointDefault) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /gitea/endpoints][%d] CreateGiteaEndpoint default %s", o._statusCode, payload) +} + +func (o *CreateGiteaEndpointDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *CreateGiteaEndpointDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/endpoints/create_github_endpoint_responses.go b/client/endpoints/create_github_endpoint_responses.go index 57016978..60961f3a 100644 --- a/client/endpoints/create_github_endpoint_responses.go +++ b/client/endpoints/create_github_endpoint_responses.go @@ -51,7 +51,7 @@ func NewCreateGithubEndpointOK() *CreateGithubEndpointOK { /* CreateGithubEndpointOK describes a response with status code 200, with default header values. -GithubEndpoint +ForgeEndpoint */ type CreateGithubEndpointOK struct { Payload garm_params.ForgeEndpoint diff --git a/client/endpoints/delete_gitea_endpoint_parameters.go b/client/endpoints/delete_gitea_endpoint_parameters.go new file mode 100644 index 00000000..f7ea5a5d --- /dev/null +++ b/client/endpoints/delete_gitea_endpoint_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package endpoints + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteGiteaEndpointParams creates a new DeleteGiteaEndpointParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteGiteaEndpointParams() *DeleteGiteaEndpointParams { + return &DeleteGiteaEndpointParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteGiteaEndpointParamsWithTimeout creates a new DeleteGiteaEndpointParams object +// with the ability to set a timeout on a request. +func NewDeleteGiteaEndpointParamsWithTimeout(timeout time.Duration) *DeleteGiteaEndpointParams { + return &DeleteGiteaEndpointParams{ + timeout: timeout, + } +} + +// NewDeleteGiteaEndpointParamsWithContext creates a new DeleteGiteaEndpointParams object +// with the ability to set a context for a request. +func NewDeleteGiteaEndpointParamsWithContext(ctx context.Context) *DeleteGiteaEndpointParams { + return &DeleteGiteaEndpointParams{ + Context: ctx, + } +} + +// NewDeleteGiteaEndpointParamsWithHTTPClient creates a new DeleteGiteaEndpointParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteGiteaEndpointParamsWithHTTPClient(client *http.Client) *DeleteGiteaEndpointParams { + return &DeleteGiteaEndpointParams{ + HTTPClient: client, + } +} + +/* +DeleteGiteaEndpointParams contains all the parameters to send to the API endpoint + + for the delete gitea endpoint operation. + + Typically these are written to a http.Request. +*/ +type DeleteGiteaEndpointParams struct { + + /* Name. + + The name of the Gitea endpoint. + */ + Name string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete gitea endpoint params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteGiteaEndpointParams) WithDefaults() *DeleteGiteaEndpointParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete gitea endpoint params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteGiteaEndpointParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete gitea endpoint params +func (o *DeleteGiteaEndpointParams) WithTimeout(timeout time.Duration) *DeleteGiteaEndpointParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete gitea endpoint params +func (o *DeleteGiteaEndpointParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete gitea endpoint params +func (o *DeleteGiteaEndpointParams) WithContext(ctx context.Context) *DeleteGiteaEndpointParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete gitea endpoint params +func (o *DeleteGiteaEndpointParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete gitea endpoint params +func (o *DeleteGiteaEndpointParams) WithHTTPClient(client *http.Client) *DeleteGiteaEndpointParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete gitea endpoint params +func (o *DeleteGiteaEndpointParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithName adds the name to the delete gitea endpoint params +func (o *DeleteGiteaEndpointParams) WithName(name string) *DeleteGiteaEndpointParams { + o.SetName(name) + return o +} + +// SetName adds the name to the delete gitea endpoint params +func (o *DeleteGiteaEndpointParams) SetName(name string) { + o.Name = name +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteGiteaEndpointParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param name + if err := r.SetPathParam("name", o.Name); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/endpoints/delete_gitea_endpoint_responses.go b/client/endpoints/delete_gitea_endpoint_responses.go new file mode 100644 index 00000000..787d6585 --- /dev/null +++ b/client/endpoints/delete_gitea_endpoint_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package endpoints + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + apiserver_params "github.com/cloudbase/garm/apiserver/params" +) + +// DeleteGiteaEndpointReader is a Reader for the DeleteGiteaEndpoint structure. +type DeleteGiteaEndpointReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteGiteaEndpointReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + result := NewDeleteGiteaEndpointDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result +} + +// NewDeleteGiteaEndpointDefault creates a DeleteGiteaEndpointDefault with default headers values +func NewDeleteGiteaEndpointDefault(code int) *DeleteGiteaEndpointDefault { + return &DeleteGiteaEndpointDefault{ + _statusCode: code, + } +} + +/* +DeleteGiteaEndpointDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type DeleteGiteaEndpointDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this delete gitea endpoint default response has a 2xx status code +func (o *DeleteGiteaEndpointDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete gitea endpoint default response has a 3xx status code +func (o *DeleteGiteaEndpointDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete gitea endpoint default response has a 4xx status code +func (o *DeleteGiteaEndpointDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete gitea endpoint default response has a 5xx status code +func (o *DeleteGiteaEndpointDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete gitea endpoint default response a status code equal to that given +func (o *DeleteGiteaEndpointDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the delete gitea endpoint default response +func (o *DeleteGiteaEndpointDefault) Code() int { + return o._statusCode +} + +func (o *DeleteGiteaEndpointDefault) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /gitea/endpoints/{name}][%d] DeleteGiteaEndpoint default %s", o._statusCode, payload) +} + +func (o *DeleteGiteaEndpointDefault) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /gitea/endpoints/{name}][%d] DeleteGiteaEndpoint default %s", o._statusCode, payload) +} + +func (o *DeleteGiteaEndpointDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *DeleteGiteaEndpointDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/endpoints/endpoints_client.go b/client/endpoints/endpoints_client.go index 9b951b2c..74019577 100644 --- a/client/endpoints/endpoints_client.go +++ b/client/endpoints/endpoints_client.go @@ -54,19 +54,67 @@ type ClientOption func(*runtime.ClientOperation) // ClientService is the interface for Client methods type ClientService interface { + CreateGiteaEndpoint(params *CreateGiteaEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateGiteaEndpointOK, error) + CreateGithubEndpoint(params *CreateGithubEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateGithubEndpointOK, error) + DeleteGiteaEndpoint(params *DeleteGiteaEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error + DeleteGithubEndpoint(params *DeleteGithubEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error + GetGiteaEndpoint(params *GetGiteaEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetGiteaEndpointOK, error) + GetGithubEndpoint(params *GetGithubEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetGithubEndpointOK, error) + ListGiteaEndpoints(params *ListGiteaEndpointsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListGiteaEndpointsOK, error) + ListGithubEndpoints(params *ListGithubEndpointsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListGithubEndpointsOK, error) + UpdateGiteaEndpoint(params *UpdateGiteaEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateGiteaEndpointOK, error) + UpdateGithubEndpoint(params *UpdateGithubEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateGithubEndpointOK, error) SetTransport(transport runtime.ClientTransport) } +/* +CreateGiteaEndpoint creates a gitea endpoint +*/ +func (a *Client) CreateGiteaEndpoint(params *CreateGiteaEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateGiteaEndpointOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateGiteaEndpointParams() + } + op := &runtime.ClientOperation{ + ID: "CreateGiteaEndpoint", + Method: "POST", + PathPattern: "/gitea/endpoints", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateGiteaEndpointReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*CreateGiteaEndpointOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateGiteaEndpointDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + /* CreateGithubEndpoint creates a git hub endpoint */ @@ -105,6 +153,38 @@ func (a *Client) CreateGithubEndpoint(params *CreateGithubEndpointParams, authIn return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) } +/* +DeleteGiteaEndpoint deletes a gitea endpoint +*/ +func (a *Client) DeleteGiteaEndpoint(params *DeleteGiteaEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteGiteaEndpointParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteGiteaEndpoint", + Method: "DELETE", + PathPattern: "/gitea/endpoints/{name}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteGiteaEndpointReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + _, err := a.transport.Submit(op) + if err != nil { + return err + } + return nil +} + /* DeleteGithubEndpoint deletes a git hub endpoint */ @@ -137,6 +217,44 @@ func (a *Client) DeleteGithubEndpoint(params *DeleteGithubEndpointParams, authIn return nil } +/* +GetGiteaEndpoint gets a gitea endpoint +*/ +func (a *Client) GetGiteaEndpoint(params *GetGiteaEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetGiteaEndpointOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetGiteaEndpointParams() + } + op := &runtime.ClientOperation{ + ID: "GetGiteaEndpoint", + Method: "GET", + PathPattern: "/gitea/endpoints/{name}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetGiteaEndpointReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetGiteaEndpointOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetGiteaEndpointDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + /* GetGithubEndpoint gets a git hub endpoint */ @@ -175,6 +293,44 @@ func (a *Client) GetGithubEndpoint(params *GetGithubEndpointParams, authInfo run return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) } +/* +ListGiteaEndpoints lists all gitea endpoints +*/ +func (a *Client) ListGiteaEndpoints(params *ListGiteaEndpointsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListGiteaEndpointsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewListGiteaEndpointsParams() + } + op := &runtime.ClientOperation{ + ID: "ListGiteaEndpoints", + Method: "GET", + PathPattern: "/gitea/endpoints", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ListGiteaEndpointsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*ListGiteaEndpointsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ListGiteaEndpointsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + /* ListGithubEndpoints lists all git hub endpoints */ @@ -213,6 +369,44 @@ func (a *Client) ListGithubEndpoints(params *ListGithubEndpointsParams, authInfo return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) } +/* +UpdateGiteaEndpoint updates a gitea endpoint +*/ +func (a *Client) UpdateGiteaEndpoint(params *UpdateGiteaEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateGiteaEndpointOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewUpdateGiteaEndpointParams() + } + op := &runtime.ClientOperation{ + ID: "UpdateGiteaEndpoint", + Method: "PUT", + PathPattern: "/gitea/endpoints/{name}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &UpdateGiteaEndpointReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*UpdateGiteaEndpointOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*UpdateGiteaEndpointDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + /* UpdateGithubEndpoint updates a git hub endpoint */ diff --git a/client/endpoints/get_gitea_endpoint_parameters.go b/client/endpoints/get_gitea_endpoint_parameters.go new file mode 100644 index 00000000..0d7f883b --- /dev/null +++ b/client/endpoints/get_gitea_endpoint_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package endpoints + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetGiteaEndpointParams creates a new GetGiteaEndpointParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetGiteaEndpointParams() *GetGiteaEndpointParams { + return &GetGiteaEndpointParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetGiteaEndpointParamsWithTimeout creates a new GetGiteaEndpointParams object +// with the ability to set a timeout on a request. +func NewGetGiteaEndpointParamsWithTimeout(timeout time.Duration) *GetGiteaEndpointParams { + return &GetGiteaEndpointParams{ + timeout: timeout, + } +} + +// NewGetGiteaEndpointParamsWithContext creates a new GetGiteaEndpointParams object +// with the ability to set a context for a request. +func NewGetGiteaEndpointParamsWithContext(ctx context.Context) *GetGiteaEndpointParams { + return &GetGiteaEndpointParams{ + Context: ctx, + } +} + +// NewGetGiteaEndpointParamsWithHTTPClient creates a new GetGiteaEndpointParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetGiteaEndpointParamsWithHTTPClient(client *http.Client) *GetGiteaEndpointParams { + return &GetGiteaEndpointParams{ + HTTPClient: client, + } +} + +/* +GetGiteaEndpointParams contains all the parameters to send to the API endpoint + + for the get gitea endpoint operation. + + Typically these are written to a http.Request. +*/ +type GetGiteaEndpointParams struct { + + /* Name. + + The name of the Gitea endpoint. + */ + Name string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get gitea endpoint params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetGiteaEndpointParams) WithDefaults() *GetGiteaEndpointParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get gitea endpoint params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetGiteaEndpointParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get gitea endpoint params +func (o *GetGiteaEndpointParams) WithTimeout(timeout time.Duration) *GetGiteaEndpointParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get gitea endpoint params +func (o *GetGiteaEndpointParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get gitea endpoint params +func (o *GetGiteaEndpointParams) WithContext(ctx context.Context) *GetGiteaEndpointParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get gitea endpoint params +func (o *GetGiteaEndpointParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get gitea endpoint params +func (o *GetGiteaEndpointParams) WithHTTPClient(client *http.Client) *GetGiteaEndpointParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get gitea endpoint params +func (o *GetGiteaEndpointParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithName adds the name to the get gitea endpoint params +func (o *GetGiteaEndpointParams) WithName(name string) *GetGiteaEndpointParams { + o.SetName(name) + return o +} + +// SetName adds the name to the get gitea endpoint params +func (o *GetGiteaEndpointParams) SetName(name string) { + o.Name = name +} + +// WriteToRequest writes these params to a swagger request +func (o *GetGiteaEndpointParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param name + if err := r.SetPathParam("name", o.Name); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/endpoints/get_gitea_endpoint_responses.go b/client/endpoints/get_gitea_endpoint_responses.go new file mode 100644 index 00000000..e4bacd03 --- /dev/null +++ b/client/endpoints/get_gitea_endpoint_responses.go @@ -0,0 +1,184 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package endpoints + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + apiserver_params "github.com/cloudbase/garm/apiserver/params" + garm_params "github.com/cloudbase/garm/params" +) + +// GetGiteaEndpointReader is a Reader for the GetGiteaEndpoint structure. +type GetGiteaEndpointReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetGiteaEndpointReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetGiteaEndpointOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetGiteaEndpointDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewGetGiteaEndpointOK creates a GetGiteaEndpointOK with default headers values +func NewGetGiteaEndpointOK() *GetGiteaEndpointOK { + return &GetGiteaEndpointOK{} +} + +/* +GetGiteaEndpointOK describes a response with status code 200, with default header values. + +ForgeEndpoint +*/ +type GetGiteaEndpointOK struct { + Payload garm_params.ForgeEndpoint +} + +// IsSuccess returns true when this get gitea endpoint o k response has a 2xx status code +func (o *GetGiteaEndpointOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get gitea endpoint o k response has a 3xx status code +func (o *GetGiteaEndpointOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get gitea endpoint o k response has a 4xx status code +func (o *GetGiteaEndpointOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get gitea endpoint o k response has a 5xx status code +func (o *GetGiteaEndpointOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get gitea endpoint o k response a status code equal to that given +func (o *GetGiteaEndpointOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get gitea endpoint o k response +func (o *GetGiteaEndpointOK) Code() int { + return 200 +} + +func (o *GetGiteaEndpointOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /gitea/endpoints/{name}][%d] getGiteaEndpointOK %s", 200, payload) +} + +func (o *GetGiteaEndpointOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /gitea/endpoints/{name}][%d] getGiteaEndpointOK %s", 200, payload) +} + +func (o *GetGiteaEndpointOK) GetPayload() garm_params.ForgeEndpoint { + return o.Payload +} + +func (o *GetGiteaEndpointOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetGiteaEndpointDefault creates a GetGiteaEndpointDefault with default headers values +func NewGetGiteaEndpointDefault(code int) *GetGiteaEndpointDefault { + return &GetGiteaEndpointDefault{ + _statusCode: code, + } +} + +/* +GetGiteaEndpointDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type GetGiteaEndpointDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this get gitea endpoint default response has a 2xx status code +func (o *GetGiteaEndpointDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get gitea endpoint default response has a 3xx status code +func (o *GetGiteaEndpointDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get gitea endpoint default response has a 4xx status code +func (o *GetGiteaEndpointDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get gitea endpoint default response has a 5xx status code +func (o *GetGiteaEndpointDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get gitea endpoint default response a status code equal to that given +func (o *GetGiteaEndpointDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the get gitea endpoint default response +func (o *GetGiteaEndpointDefault) Code() int { + return o._statusCode +} + +func (o *GetGiteaEndpointDefault) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /gitea/endpoints/{name}][%d] GetGiteaEndpoint default %s", o._statusCode, payload) +} + +func (o *GetGiteaEndpointDefault) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /gitea/endpoints/{name}][%d] GetGiteaEndpoint default %s", o._statusCode, payload) +} + +func (o *GetGiteaEndpointDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *GetGiteaEndpointDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/endpoints/get_github_endpoint_responses.go b/client/endpoints/get_github_endpoint_responses.go index 4b4881cd..e2b97a60 100644 --- a/client/endpoints/get_github_endpoint_responses.go +++ b/client/endpoints/get_github_endpoint_responses.go @@ -51,7 +51,7 @@ func NewGetGithubEndpointOK() *GetGithubEndpointOK { /* GetGithubEndpointOK describes a response with status code 200, with default header values. -GithubEndpoint +ForgeEndpoint */ type GetGithubEndpointOK struct { Payload garm_params.ForgeEndpoint diff --git a/client/endpoints/list_gitea_endpoints_parameters.go b/client/endpoints/list_gitea_endpoints_parameters.go new file mode 100644 index 00000000..93ec6ae6 --- /dev/null +++ b/client/endpoints/list_gitea_endpoints_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package endpoints + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewListGiteaEndpointsParams creates a new ListGiteaEndpointsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewListGiteaEndpointsParams() *ListGiteaEndpointsParams { + return &ListGiteaEndpointsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewListGiteaEndpointsParamsWithTimeout creates a new ListGiteaEndpointsParams object +// with the ability to set a timeout on a request. +func NewListGiteaEndpointsParamsWithTimeout(timeout time.Duration) *ListGiteaEndpointsParams { + return &ListGiteaEndpointsParams{ + timeout: timeout, + } +} + +// NewListGiteaEndpointsParamsWithContext creates a new ListGiteaEndpointsParams object +// with the ability to set a context for a request. +func NewListGiteaEndpointsParamsWithContext(ctx context.Context) *ListGiteaEndpointsParams { + return &ListGiteaEndpointsParams{ + Context: ctx, + } +} + +// NewListGiteaEndpointsParamsWithHTTPClient creates a new ListGiteaEndpointsParams object +// with the ability to set a custom HTTPClient for a request. +func NewListGiteaEndpointsParamsWithHTTPClient(client *http.Client) *ListGiteaEndpointsParams { + return &ListGiteaEndpointsParams{ + HTTPClient: client, + } +} + +/* +ListGiteaEndpointsParams contains all the parameters to send to the API endpoint + + for the list gitea endpoints operation. + + Typically these are written to a http.Request. +*/ +type ListGiteaEndpointsParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the list gitea endpoints params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListGiteaEndpointsParams) WithDefaults() *ListGiteaEndpointsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the list gitea endpoints params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListGiteaEndpointsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the list gitea endpoints params +func (o *ListGiteaEndpointsParams) WithTimeout(timeout time.Duration) *ListGiteaEndpointsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list gitea endpoints params +func (o *ListGiteaEndpointsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list gitea endpoints params +func (o *ListGiteaEndpointsParams) WithContext(ctx context.Context) *ListGiteaEndpointsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list gitea endpoints params +func (o *ListGiteaEndpointsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list gitea endpoints params +func (o *ListGiteaEndpointsParams) WithHTTPClient(client *http.Client) *ListGiteaEndpointsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list gitea endpoints params +func (o *ListGiteaEndpointsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListGiteaEndpointsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/endpoints/list_gitea_endpoints_responses.go b/client/endpoints/list_gitea_endpoints_responses.go new file mode 100644 index 00000000..0fdd90ec --- /dev/null +++ b/client/endpoints/list_gitea_endpoints_responses.go @@ -0,0 +1,184 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package endpoints + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + apiserver_params "github.com/cloudbase/garm/apiserver/params" + garm_params "github.com/cloudbase/garm/params" +) + +// ListGiteaEndpointsReader is a Reader for the ListGiteaEndpoints structure. +type ListGiteaEndpointsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListGiteaEndpointsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListGiteaEndpointsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewListGiteaEndpointsDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewListGiteaEndpointsOK creates a ListGiteaEndpointsOK with default headers values +func NewListGiteaEndpointsOK() *ListGiteaEndpointsOK { + return &ListGiteaEndpointsOK{} +} + +/* +ListGiteaEndpointsOK describes a response with status code 200, with default header values. + +ForgeEndpoints +*/ +type ListGiteaEndpointsOK struct { + Payload garm_params.ForgeEndpoints +} + +// IsSuccess returns true when this list gitea endpoints o k response has a 2xx status code +func (o *ListGiteaEndpointsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this list gitea endpoints o k response has a 3xx status code +func (o *ListGiteaEndpointsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list gitea endpoints o k response has a 4xx status code +func (o *ListGiteaEndpointsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this list gitea endpoints o k response has a 5xx status code +func (o *ListGiteaEndpointsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this list gitea endpoints o k response a status code equal to that given +func (o *ListGiteaEndpointsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the list gitea endpoints o k response +func (o *ListGiteaEndpointsOK) Code() int { + return 200 +} + +func (o *ListGiteaEndpointsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /gitea/endpoints][%d] listGiteaEndpointsOK %s", 200, payload) +} + +func (o *ListGiteaEndpointsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /gitea/endpoints][%d] listGiteaEndpointsOK %s", 200, payload) +} + +func (o *ListGiteaEndpointsOK) GetPayload() garm_params.ForgeEndpoints { + return o.Payload +} + +func (o *ListGiteaEndpointsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewListGiteaEndpointsDefault creates a ListGiteaEndpointsDefault with default headers values +func NewListGiteaEndpointsDefault(code int) *ListGiteaEndpointsDefault { + return &ListGiteaEndpointsDefault{ + _statusCode: code, + } +} + +/* +ListGiteaEndpointsDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type ListGiteaEndpointsDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this list gitea endpoints default response has a 2xx status code +func (o *ListGiteaEndpointsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this list gitea endpoints default response has a 3xx status code +func (o *ListGiteaEndpointsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this list gitea endpoints default response has a 4xx status code +func (o *ListGiteaEndpointsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this list gitea endpoints default response has a 5xx status code +func (o *ListGiteaEndpointsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this list gitea endpoints default response a status code equal to that given +func (o *ListGiteaEndpointsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the list gitea endpoints default response +func (o *ListGiteaEndpointsDefault) Code() int { + return o._statusCode +} + +func (o *ListGiteaEndpointsDefault) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /gitea/endpoints][%d] ListGiteaEndpoints default %s", o._statusCode, payload) +} + +func (o *ListGiteaEndpointsDefault) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /gitea/endpoints][%d] ListGiteaEndpoints default %s", o._statusCode, payload) +} + +func (o *ListGiteaEndpointsDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *ListGiteaEndpointsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/endpoints/list_github_endpoints_responses.go b/client/endpoints/list_github_endpoints_responses.go index f7b10a1c..33485f9b 100644 --- a/client/endpoints/list_github_endpoints_responses.go +++ b/client/endpoints/list_github_endpoints_responses.go @@ -51,7 +51,7 @@ func NewListGithubEndpointsOK() *ListGithubEndpointsOK { /* ListGithubEndpointsOK describes a response with status code 200, with default header values. -GithubEndpoints +ForgeEndpoints */ type ListGithubEndpointsOK struct { Payload garm_params.ForgeEndpoints diff --git a/client/endpoints/update_gitea_endpoint_parameters.go b/client/endpoints/update_gitea_endpoint_parameters.go new file mode 100644 index 00000000..bfd18e2e --- /dev/null +++ b/client/endpoints/update_gitea_endpoint_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package endpoints + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + garm_params "github.com/cloudbase/garm/params" +) + +// NewUpdateGiteaEndpointParams creates a new UpdateGiteaEndpointParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewUpdateGiteaEndpointParams() *UpdateGiteaEndpointParams { + return &UpdateGiteaEndpointParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewUpdateGiteaEndpointParamsWithTimeout creates a new UpdateGiteaEndpointParams object +// with the ability to set a timeout on a request. +func NewUpdateGiteaEndpointParamsWithTimeout(timeout time.Duration) *UpdateGiteaEndpointParams { + return &UpdateGiteaEndpointParams{ + timeout: timeout, + } +} + +// NewUpdateGiteaEndpointParamsWithContext creates a new UpdateGiteaEndpointParams object +// with the ability to set a context for a request. +func NewUpdateGiteaEndpointParamsWithContext(ctx context.Context) *UpdateGiteaEndpointParams { + return &UpdateGiteaEndpointParams{ + Context: ctx, + } +} + +// NewUpdateGiteaEndpointParamsWithHTTPClient creates a new UpdateGiteaEndpointParams object +// with the ability to set a custom HTTPClient for a request. +func NewUpdateGiteaEndpointParamsWithHTTPClient(client *http.Client) *UpdateGiteaEndpointParams { + return &UpdateGiteaEndpointParams{ + HTTPClient: client, + } +} + +/* +UpdateGiteaEndpointParams contains all the parameters to send to the API endpoint + + for the update gitea endpoint operation. + + Typically these are written to a http.Request. +*/ +type UpdateGiteaEndpointParams struct { + + /* Body. + + Parameters used when updating a Gitea endpoint. + */ + Body garm_params.UpdateGiteaEndpointParams + + /* Name. + + The name of the Gitea endpoint. + */ + Name string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the update gitea endpoint params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UpdateGiteaEndpointParams) WithDefaults() *UpdateGiteaEndpointParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the update gitea endpoint params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UpdateGiteaEndpointParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the update gitea endpoint params +func (o *UpdateGiteaEndpointParams) WithTimeout(timeout time.Duration) *UpdateGiteaEndpointParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the update gitea endpoint params +func (o *UpdateGiteaEndpointParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the update gitea endpoint params +func (o *UpdateGiteaEndpointParams) WithContext(ctx context.Context) *UpdateGiteaEndpointParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the update gitea endpoint params +func (o *UpdateGiteaEndpointParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the update gitea endpoint params +func (o *UpdateGiteaEndpointParams) WithHTTPClient(client *http.Client) *UpdateGiteaEndpointParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the update gitea endpoint params +func (o *UpdateGiteaEndpointParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the update gitea endpoint params +func (o *UpdateGiteaEndpointParams) WithBody(body garm_params.UpdateGiteaEndpointParams) *UpdateGiteaEndpointParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the update gitea endpoint params +func (o *UpdateGiteaEndpointParams) SetBody(body garm_params.UpdateGiteaEndpointParams) { + o.Body = body +} + +// WithName adds the name to the update gitea endpoint params +func (o *UpdateGiteaEndpointParams) WithName(name string) *UpdateGiteaEndpointParams { + o.SetName(name) + return o +} + +// SetName adds the name to the update gitea endpoint params +func (o *UpdateGiteaEndpointParams) SetName(name string) { + o.Name = name +} + +// WriteToRequest writes these params to a swagger request +func (o *UpdateGiteaEndpointParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + + // path param name + if err := r.SetPathParam("name", o.Name); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/endpoints/update_gitea_endpoint_responses.go b/client/endpoints/update_gitea_endpoint_responses.go new file mode 100644 index 00000000..052f45fa --- /dev/null +++ b/client/endpoints/update_gitea_endpoint_responses.go @@ -0,0 +1,184 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package endpoints + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + apiserver_params "github.com/cloudbase/garm/apiserver/params" + garm_params "github.com/cloudbase/garm/params" +) + +// UpdateGiteaEndpointReader is a Reader for the UpdateGiteaEndpoint structure. +type UpdateGiteaEndpointReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UpdateGiteaEndpointReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUpdateGiteaEndpointOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewUpdateGiteaEndpointDefault(response.Code()) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + if response.Code()/100 == 2 { + return result, nil + } + return nil, result + } +} + +// NewUpdateGiteaEndpointOK creates a UpdateGiteaEndpointOK with default headers values +func NewUpdateGiteaEndpointOK() *UpdateGiteaEndpointOK { + return &UpdateGiteaEndpointOK{} +} + +/* +UpdateGiteaEndpointOK describes a response with status code 200, with default header values. + +ForgeEndpoint +*/ +type UpdateGiteaEndpointOK struct { + Payload garm_params.ForgeEndpoint +} + +// IsSuccess returns true when this update gitea endpoint o k response has a 2xx status code +func (o *UpdateGiteaEndpointOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this update gitea endpoint o k response has a 3xx status code +func (o *UpdateGiteaEndpointOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this update gitea endpoint o k response has a 4xx status code +func (o *UpdateGiteaEndpointOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this update gitea endpoint o k response has a 5xx status code +func (o *UpdateGiteaEndpointOK) IsServerError() bool { + return false +} + +// IsCode returns true when this update gitea endpoint o k response a status code equal to that given +func (o *UpdateGiteaEndpointOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the update gitea endpoint o k response +func (o *UpdateGiteaEndpointOK) Code() int { + return 200 +} + +func (o *UpdateGiteaEndpointOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /gitea/endpoints/{name}][%d] updateGiteaEndpointOK %s", 200, payload) +} + +func (o *UpdateGiteaEndpointOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /gitea/endpoints/{name}][%d] updateGiteaEndpointOK %s", 200, payload) +} + +func (o *UpdateGiteaEndpointOK) GetPayload() garm_params.ForgeEndpoint { + return o.Payload +} + +func (o *UpdateGiteaEndpointOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdateGiteaEndpointDefault creates a UpdateGiteaEndpointDefault with default headers values +func NewUpdateGiteaEndpointDefault(code int) *UpdateGiteaEndpointDefault { + return &UpdateGiteaEndpointDefault{ + _statusCode: code, + } +} + +/* +UpdateGiteaEndpointDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type UpdateGiteaEndpointDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this update gitea endpoint default response has a 2xx status code +func (o *UpdateGiteaEndpointDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this update gitea endpoint default response has a 3xx status code +func (o *UpdateGiteaEndpointDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this update gitea endpoint default response has a 4xx status code +func (o *UpdateGiteaEndpointDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this update gitea endpoint default response has a 5xx status code +func (o *UpdateGiteaEndpointDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this update gitea endpoint default response a status code equal to that given +func (o *UpdateGiteaEndpointDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the update gitea endpoint default response +func (o *UpdateGiteaEndpointDefault) Code() int { + return o._statusCode +} + +func (o *UpdateGiteaEndpointDefault) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /gitea/endpoints/{name}][%d] UpdateGiteaEndpoint default %s", o._statusCode, payload) +} + +func (o *UpdateGiteaEndpointDefault) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /gitea/endpoints/{name}][%d] UpdateGiteaEndpoint default %s", o._statusCode, payload) +} + +func (o *UpdateGiteaEndpointDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *UpdateGiteaEndpointDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/endpoints/update_github_endpoint_responses.go b/client/endpoints/update_github_endpoint_responses.go index 969d6bbd..27cd4a71 100644 --- a/client/endpoints/update_github_endpoint_responses.go +++ b/client/endpoints/update_github_endpoint_responses.go @@ -51,7 +51,7 @@ func NewUpdateGithubEndpointOK() *UpdateGithubEndpointOK { /* UpdateGithubEndpointOK describes a response with status code 200, with default header values. -GithubEndpoint +ForgeEndpoint */ type UpdateGithubEndpointOK struct { Payload garm_params.ForgeEndpoint diff --git a/cmd/garm-cli/cmd/gitea.go b/cmd/garm-cli/cmd/gitea.go new file mode 100644 index 00000000..10d086bd --- /dev/null +++ b/cmd/garm-cli/cmd/gitea.go @@ -0,0 +1,21 @@ +package cmd + +import "github.com/spf13/cobra" + +// giteaCmd represents the the gitea command. This command has a set +// of subcommands that allow configuring and managing Gitea endpoints +// and credentials. +var giteaCmd = &cobra.Command{ + Use: "gitea", + Aliases: []string{"gt"}, + SilenceUsage: true, + Short: "Manage Gitea resources", + Long: `Manage Gitea related resources. + +This command allows you to configure and manage Gitea endpoints and credentials`, + Run: nil, +} + +func init() { + rootCmd.AddCommand(giteaCmd) +} diff --git a/cmd/garm-cli/cmd/gitea_credentials.go b/cmd/garm-cli/cmd/gitea_credentials.go new file mode 100644 index 00000000..c744c8a7 --- /dev/null +++ b/cmd/garm-cli/cmd/gitea_credentials.go @@ -0,0 +1,317 @@ +// Copyright 2022 Cloudbase Solutions SRL +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. + +package cmd + +import ( + "fmt" + "strconv" + + "github.com/jedib0t/go-pretty/v6/table" + "github.com/spf13/cobra" + + apiClientCreds "github.com/cloudbase/garm/client/credentials" + "github.com/cloudbase/garm/cmd/garm-cli/common" + "github.com/cloudbase/garm/params" +) + +// giteaCredentialsCmd represents the gitea credentials command +var giteaCredentialsCmd = &cobra.Command{ + Use: "credentials", + Aliases: []string{"creds"}, + Short: "Manage gitea credentials", + Long: `Manage Gitea credentials stored in GARM. + +This command allows you to add, update, list and delete Gitea credentials.`, + Run: nil, +} + +var giteaCredentialsListCmd = &cobra.Command{ + Use: "list", + Aliases: []string{"ls"}, + Short: "List configured gitea credentials", + Long: `List the names of the gitea personal access tokens available to the garm.`, + SilenceUsage: true, + RunE: func(_ *cobra.Command, _ []string) error { + if needsInit { + return errNeedsInitError + } + + listCredsReq := apiClientCreds.NewListGiteaCredentialsParams() + response, err := apiCli.Credentials.ListGiteaCredentials(listCredsReq, authToken) + if err != nil { + return err + } + formatGiteaCredentials(response.Payload) + return nil + }, +} + +var giteaCredentialsShowCmd = &cobra.Command{ + Use: "show", + Aliases: []string{"get"}, + Short: "Show details of a configured gitea credential", + Long: `Show the details of a configured gitea credential.`, + SilenceUsage: true, + RunE: func(_ *cobra.Command, args []string) error { + if needsInit { + return errNeedsInitError + } + + if len(args) < 1 { + return fmt.Errorf("missing required argument: credential ID") + } + + credID, err := strconv.ParseInt(args[0], 10, 64) + if err != nil { + return fmt.Errorf("invalid credential ID: %s", args[0]) + } + showCredsReq := apiClientCreds.NewGetGiteaCredentialsParams().WithID(credID) + response, err := apiCli.Credentials.GetGiteaCredentials(showCredsReq, authToken) + if err != nil { + return err + } + formatOneGiteaCredential(response.Payload) + return nil + }, +} + +var giteaCredentialsUpdateCmd = &cobra.Command{ + Use: "update", + Short: "Update a gitea credential", + Long: "Update a gitea credential", + SilenceUsage: true, + RunE: func(_ *cobra.Command, args []string) error { + if needsInit { + return errNeedsInitError + } + + if len(args) < 1 { + return fmt.Errorf("missing required argument: credential ID") + } + + if len(args) > 1 { + return fmt.Errorf("too many arguments") + } + + credID, err := strconv.ParseInt(args[0], 10, 64) + if err != nil { + return fmt.Errorf("invalid credential ID: %s", args[0]) + } + + updateParams, err := parseGiteaCredentialsUpdateParams() + if err != nil { + return err + } + + updateCredsReq := apiClientCreds.NewUpdateGiteaCredentialsParams().WithID(credID) + updateCredsReq.Body = updateParams + + response, err := apiCli.Credentials.UpdateGiteaCredentials(updateCredsReq, authToken) + if err != nil { + return err + } + formatOneGiteaCredential(response.Payload) + return nil + }, +} + +var giteaCredentialsDeleteCmd = &cobra.Command{ + Use: "delete", + Aliases: []string{"remove", "rm"}, + Short: "Delete a gitea credential", + Long: "Delete a gitea credential", + SilenceUsage: true, + RunE: func(_ *cobra.Command, args []string) error { + if needsInit { + return errNeedsInitError + } + + if len(args) < 1 { + return fmt.Errorf("missing required argument: credential ID") + } + + if len(args) > 1 { + return fmt.Errorf("too many arguments") + } + + credID, err := strconv.ParseInt(args[0], 10, 64) + if err != nil { + return fmt.Errorf("invalid credential ID: %s", args[0]) + } + + deleteCredsReq := apiClientCreds.NewDeleteGiteaCredentialsParams().WithID(credID) + if err := apiCli.Credentials.DeleteGiteaCredentials(deleteCredsReq, authToken); err != nil { + return err + } + return nil + }, +} + +var giteaCredentialsAddCmd = &cobra.Command{ + Use: "add", + Short: "Add a gitea credential", + Long: "Add a gitea credential", + SilenceUsage: true, + RunE: func(_ *cobra.Command, args []string) error { + if needsInit { + return errNeedsInitError + } + + if len(args) > 0 { + return fmt.Errorf("too many arguments") + } + + addParams, err := parseGiteaCredentialsAddParams() + if err != nil { + return err + } + + addCredsReq := apiClientCreds.NewCreateGiteaCredentialsParams() + addCredsReq.Body = addParams + + response, err := apiCli.Credentials.CreateGiteaCredentials(addCredsReq, authToken) + if err != nil { + return err + } + formatOneGiteaCredential(response.Payload) + return nil + }, +} + +func init() { + giteaCredentialsUpdateCmd.Flags().StringVar(&credentialsName, "name", "", "Name of the credential") + giteaCredentialsUpdateCmd.Flags().StringVar(&credentialsDescription, "description", "", "Description of the credential") + giteaCredentialsUpdateCmd.Flags().StringVar(&credentialsOAuthToken, "pat-oauth-token", "", "If the credential is a personal access token, the OAuth token") + + giteaCredentialsListCmd.Flags().BoolVarP(&long, "long", "l", false, "Include additional info.") + + giteaCredentialsAddCmd.Flags().StringVar(&credentialsName, "name", "", "Name of the credential") + giteaCredentialsAddCmd.Flags().StringVar(&credentialsDescription, "description", "", "Description of the credential") + giteaCredentialsAddCmd.Flags().StringVar(&credentialsOAuthToken, "pat-oauth-token", "", "If the credential is a personal access token, the OAuth token") + giteaCredentialsAddCmd.Flags().StringVar(&credentialsType, "auth-type", "", "The type of the credential") + giteaCredentialsAddCmd.Flags().StringVar(&credentialsEndpoint, "endpoint", "", "The endpoint to associate the credential with") + + giteaCredentialsAddCmd.MarkFlagRequired("name") + giteaCredentialsAddCmd.MarkFlagRequired("auth-type") + giteaCredentialsAddCmd.MarkFlagRequired("description") + giteaCredentialsAddCmd.MarkFlagRequired("endpoint") + + giteaCredentialsCmd.AddCommand( + giteaCredentialsListCmd, + giteaCredentialsShowCmd, + giteaCredentialsUpdateCmd, + giteaCredentialsDeleteCmd, + giteaCredentialsAddCmd, + ) + giteaCmd.AddCommand(giteaCredentialsCmd) +} + +func parseGiteaCredentialsAddParams() (ret params.CreateGiteaCredentialsParams, err error) { + ret.Name = credentialsName + ret.Description = credentialsDescription + ret.AuthType = params.ForgeAuthType(credentialsType) + ret.Endpoint = credentialsEndpoint + switch ret.AuthType { + case params.ForgeAuthTypePAT: + ret.PAT.OAuth2Token = credentialsOAuthToken + default: + return params.CreateGiteaCredentialsParams{}, fmt.Errorf("invalid auth type: %s (supported are: pat)", credentialsType) + } + + return ret, nil +} + +func parseGiteaCredentialsUpdateParams() (params.UpdateGiteaCredentialsParams, error) { + var updateParams params.UpdateGiteaCredentialsParams + + if credentialsName != "" { + updateParams.Name = &credentialsName + } + + if credentialsDescription != "" { + updateParams.Description = &credentialsDescription + } + + if credentialsOAuthToken != "" { + if updateParams.PAT == nil { + updateParams.PAT = ¶ms.GithubPAT{} + } + updateParams.PAT.OAuth2Token = credentialsOAuthToken + } + + return updateParams, nil +} + +func formatGiteaCredentials(creds []params.ForgeCredentials) { + if outputFormat == common.OutputFormatJSON { + printAsJSON(creds) + return + } + t := table.NewWriter() + header := table.Row{"ID", "Name", "Description", "Base URL", "API URL", "Type"} + if long { + header = append(header, "Created At", "Updated At") + } + t.AppendHeader(header) + for _, val := range creds { + row := table.Row{val.ID, val.Name, val.Description, val.BaseURL, val.APIBaseURL, val.AuthType} + if long { + row = append(row, val.CreatedAt, val.UpdatedAt) + } + t.AppendRow(row) + t.AppendSeparator() + } + fmt.Println(t.Render()) +} + +func formatOneGiteaCredential(cred params.ForgeCredentials) { + if outputFormat == common.OutputFormatJSON { + printAsJSON(cred) + return + } + t := table.NewWriter() + header := table.Row{"Field", "Value"} + t.AppendHeader(header) + + t.AppendRow(table.Row{"ID", cred.ID}) + t.AppendRow(table.Row{"Created At", cred.CreatedAt}) + t.AppendRow(table.Row{"Updated At", cred.UpdatedAt}) + t.AppendRow(table.Row{"Name", cred.Name}) + t.AppendRow(table.Row{"Description", cred.Description}) + t.AppendRow(table.Row{"Base URL", cred.BaseURL}) + t.AppendRow(table.Row{"API URL", cred.APIBaseURL}) + t.AppendRow(table.Row{"Type", cred.AuthType}) + t.AppendRow(table.Row{"Endpoint", cred.Endpoint.Name}) + + if len(cred.Repositories) > 0 { + t.AppendRow(table.Row{"", ""}) + for _, repo := range cred.Repositories { + t.AppendRow(table.Row{"Repositories", repo.String()}) + } + } + + if len(cred.Organizations) > 0 { + t.AppendRow(table.Row{"", ""}) + for _, org := range cred.Organizations { + t.AppendRow(table.Row{"Organizations", org.Name}) + } + } + + t.SetColumnConfigs([]table.ColumnConfig{ + {Number: 1, AutoMerge: true}, + {Number: 2, AutoMerge: false, WidthMax: 100}, + }) + fmt.Println(t.Render()) +} diff --git a/cmd/garm-cli/cmd/gitea_endpoints.go b/cmd/garm-cli/cmd/gitea_endpoints.go new file mode 100644 index 00000000..d3504f17 --- /dev/null +++ b/cmd/garm-cli/cmd/gitea_endpoints.go @@ -0,0 +1,218 @@ +package cmd + +import ( + "fmt" + + "github.com/spf13/cobra" + + apiClientEndpoints "github.com/cloudbase/garm/client/endpoints" + "github.com/cloudbase/garm/params" +) + +var giteaEndpointCmd = &cobra.Command{ + Use: "endpoint", + SilenceUsage: true, + Short: "Manage Gitea endpoints", + Long: `Manage Gitea endpoints. + +This command allows you to configure and manage Gitea endpoints`, + Run: nil, +} + +var giteaEndpointListCmd = &cobra.Command{ + Use: "list", + Aliases: []string{"ls"}, + SilenceUsage: true, + Short: "List Gitea endpoints", + Long: `List all configured Gitea endpoints.`, + RunE: func(_ *cobra.Command, _ []string) error { + if needsInit { + return errNeedsInitError + } + + newListReq := apiClientEndpoints.NewListGiteaEndpointsParams() + response, err := apiCli.Endpoints.ListGiteaEndpoints(newListReq, authToken) + if err != nil { + return err + } + formatEndpoints(response.Payload) + return nil + }, +} + +var giteaEndpointShowCmd = &cobra.Command{ + Use: "show", + Aliases: []string{"get"}, + SilenceUsage: true, + Short: "Show Gitea endpoint", + Long: `Show details of a Gitea endpoint.`, + RunE: func(_ *cobra.Command, args []string) error { + if needsInit { + return errNeedsInitError + } + if len(args) == 0 { + return fmt.Errorf("requires an endpoint name") + } + if len(args) > 1 { + return fmt.Errorf("too many arguments") + } + + newShowReq := apiClientEndpoints.NewGetGiteaEndpointParams() + newShowReq.Name = args[0] + response, err := apiCli.Endpoints.GetGiteaEndpoint(newShowReq, authToken) + if err != nil { + return err + } + formatOneEndpoint(response.Payload) + return nil + }, +} + +var giteaEndpointCreateCmd = &cobra.Command{ + Use: "create", + SilenceUsage: true, + Short: "Create Gitea endpoint", + Long: `Create a new Gitea endpoint.`, + RunE: func(_ *cobra.Command, _ []string) error { + if needsInit { + return errNeedsInitError + } + + createParams, err := parseGiteaCreateParams() + if err != nil { + return err + } + + newCreateReq := apiClientEndpoints.NewCreateGiteaEndpointParams() + newCreateReq.Body = createParams + + response, err := apiCli.Endpoints.CreateGiteaEndpoint(newCreateReq, authToken) + if err != nil { + return err + } + formatOneEndpoint(response.Payload) + return nil + }, +} + +var giteaEndpointDeleteCmd = &cobra.Command{ + Use: "delete", + Aliases: []string{"remove", "rm"}, + SilenceUsage: true, + Short: "Delete Gitea endpoint", + Long: "Delete a Gitea endpoint", + RunE: func(_ *cobra.Command, args []string) error { + if needsInit { + return errNeedsInitError + } + if len(args) == 0 { + return fmt.Errorf("requires an endpoint name") + } + if len(args) > 1 { + return fmt.Errorf("too many arguments") + } + + newDeleteReq := apiClientEndpoints.NewDeleteGiteaEndpointParams() + newDeleteReq.Name = args[0] + if err := apiCli.Endpoints.DeleteGiteaEndpoint(newDeleteReq, authToken); err != nil { + return err + } + return nil + }, +} + +var giteaEndpointUpdateCmd = &cobra.Command{ + Use: "update", + Short: "Update Gitea endpoint", + Long: "Update a Gitea endpoint", + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + if needsInit { + return errNeedsInitError + } + if len(args) == 0 { + return fmt.Errorf("requires an endpoint name") + } + if len(args) > 1 { + return fmt.Errorf("too many arguments") + } + + updateParams := params.UpdateGiteaEndpointParams{} + + if cmd.Flags().Changed("ca-cert-path") { + cert, err := parseAndReadCABundle() + if err != nil { + return err + } + updateParams.CACertBundle = cert + } + + if cmd.Flags().Changed("description") { + updateParams.Description = &endpointDescription + } + + if cmd.Flags().Changed("base-url") { + updateParams.BaseURL = &endpointBaseURL + } + + if cmd.Flags().Changed("api-base-url") { + updateParams.APIBaseURL = &endpointAPIBaseURL + } + + newEndpointUpdateReq := apiClientEndpoints.NewUpdateGiteaEndpointParams() + newEndpointUpdateReq.Name = args[0] + newEndpointUpdateReq.Body = updateParams + + response, err := apiCli.Endpoints.UpdateGiteaEndpoint(newEndpointUpdateReq, authToken) + if err != nil { + return err + } + formatOneEndpoint(response.Payload) + return nil + }, +} + +func init() { + giteaEndpointCreateCmd.Flags().StringVar(&endpointName, "name", "", "Name of the Gitea endpoint") + giteaEndpointCreateCmd.Flags().StringVar(&endpointDescription, "description", "", "Description for the github endpoint") + giteaEndpointCreateCmd.Flags().StringVar(&endpointBaseURL, "base-url", "", "Base URL of the Gitea endpoint") + giteaEndpointCreateCmd.Flags().StringVar(&endpointAPIBaseURL, "api-base-url", "", "API Base URL of the Gitea endpoint") + giteaEndpointCreateCmd.Flags().StringVar(&endpointCACertPath, "ca-cert-path", "", "CA Cert Path of the Gitea endpoint") + + giteaEndpointListCmd.Flags().BoolVarP(&long, "long", "l", false, "Include additional info.") + + giteaEndpointCreateCmd.MarkFlagRequired("name") + giteaEndpointCreateCmd.MarkFlagRequired("base-url") + giteaEndpointCreateCmd.MarkFlagRequired("api-base-url") + + giteaEndpointUpdateCmd.Flags().StringVar(&endpointDescription, "description", "", "Description for the gitea endpoint") + giteaEndpointUpdateCmd.Flags().StringVar(&endpointBaseURL, "base-url", "", "Base URL of the Gitea endpoint") + giteaEndpointUpdateCmd.Flags().StringVar(&endpointAPIBaseURL, "api-base-url", "", "API Base URL of the Gitea endpoint") + giteaEndpointUpdateCmd.Flags().StringVar(&endpointCACertPath, "ca-cert-path", "", "CA Cert Path of the Gitea endpoint") + + giteaEndpointCmd.AddCommand( + giteaEndpointListCmd, + giteaEndpointShowCmd, + giteaEndpointCreateCmd, + giteaEndpointDeleteCmd, + giteaEndpointUpdateCmd, + ) + + giteaCmd.AddCommand(giteaEndpointCmd) +} + +func parseGiteaCreateParams() (params.CreateGiteaEndpointParams, error) { + certBundleBytes, err := parseAndReadCABundle() + if err != nil { + return params.CreateGiteaEndpointParams{}, err + } + + ret := params.CreateGiteaEndpointParams{ + Name: endpointName, + BaseURL: endpointBaseURL, + APIBaseURL: endpointAPIBaseURL, + Description: endpointDescription, + CACertBundle: certBundleBytes, + } + return ret, nil +} diff --git a/cmd/garm-cli/cmd/github_credentials.go b/cmd/garm-cli/cmd/github_credentials.go index fb3853d8..ae2374f6 100644 --- a/cmd/garm-cli/cmd/github_credentials.go +++ b/cmd/garm-cli/cmd/github_credentials.go @@ -344,7 +344,7 @@ func parseCredentialsUpdateParams() (params.UpdateGithubCredentialsParams, error return updateParams, nil } -func formatGithubCredentials(creds []params.GithubCredentials) { +func formatGithubCredentials(creds []params.ForgeCredentials) { if outputFormat == common.OutputFormatJSON { printAsJSON(creds) return @@ -366,7 +366,7 @@ func formatGithubCredentials(creds []params.GithubCredentials) { fmt.Println(t.Render()) } -func formatOneGithubCredential(cred params.GithubCredentials) { +func formatOneGithubCredential(cred params.ForgeCredentials) { if outputFormat == common.OutputFormatJSON { printAsJSON(cred) return diff --git a/cmd/garm-cli/cmd/github_endpoints.go b/cmd/garm-cli/cmd/github_endpoints.go index f119a1a2..fbdca86c 100644 --- a/cmd/garm-cli/cmd/github_endpoints.go +++ b/cmd/garm-cli/cmd/github_endpoints.go @@ -145,7 +145,7 @@ var githubEndpointUpdateCmd = &cobra.Command{ updateParams := params.UpdateGithubEndpointParams{} if cmd.Flags().Changed("ca-cert-path") { - cert, err := parseReadAndParsCABundle() + cert, err := parseAndReadCABundle() if err != nil { return err } @@ -213,7 +213,7 @@ func init() { githubCmd.AddCommand(githubEndpointCmd) } -func parseReadAndParsCABundle() ([]byte, error) { +func parseAndReadCABundle() ([]byte, error) { if endpointCACertPath == "" { return nil, nil } @@ -236,7 +236,7 @@ func parseReadAndParsCABundle() ([]byte, error) { } func parseCreateParams() (params.CreateGithubEndpointParams, error) { - certBundleBytes, err := parseReadAndParsCABundle() + certBundleBytes, err := parseAndReadCABundle() if err != nil { return params.CreateGithubEndpointParams{}, err } @@ -287,7 +287,9 @@ func formatOneEndpoint(endpoint params.ForgeEndpoint) { t.AppendRow([]interface{}{"Created At", endpoint.CreatedAt}) t.AppendRow([]interface{}{"Updated At", endpoint.UpdatedAt}) t.AppendRow([]interface{}{"Base URL", endpoint.BaseURL}) - t.AppendRow([]interface{}{"Upload URL", endpoint.UploadBaseURL}) + if endpoint.UploadBaseURL != "" { + t.AppendRow([]interface{}{"Upload URL", endpoint.UploadBaseURL}) + } t.AppendRow([]interface{}{"API Base URL", endpoint.APIBaseURL}) if len(endpoint.CACertBundle) > 0 { t.AppendRow([]interface{}{"CA Cert Bundle", string(endpoint.CACertBundle)}) diff --git a/cmd/garm-cli/cmd/repository.go b/cmd/garm-cli/cmd/repository.go index 1c453836..b24cf039 100644 --- a/cmd/garm-cli/cmd/repository.go +++ b/cmd/garm-cli/cmd/repository.go @@ -31,6 +31,7 @@ var ( repoName string repoWebhookSecret string repoCreds string + forgeType string randomWebhookSecret bool insecureRepoWebhook bool keepRepoWebhook bool @@ -169,6 +170,7 @@ var repoAddCmd = &cobra.Command{ Name: repoName, WebhookSecret: repoWebhookSecret, CredentialsName: repoCreds, + ForgeType: params.EndpointType(forgeType), PoolBalancerType: params.PoolBalancerType(poolBalancerType), } response, err := apiCli.Repositories.CreateRepo(newRepoReq, authToken) @@ -309,6 +311,7 @@ func init() { repoAddCmd.Flags().StringVar(&repoOwner, "owner", "", "The owner of this repository") repoAddCmd.Flags().StringVar(&poolBalancerType, "pool-balancer-type", string(params.PoolBalancerTypeRoundRobin), "The balancing strategy to use when creating runners in pools matching requested labels.") repoAddCmd.Flags().StringVar(&repoName, "name", "", "The name of the repository") + repoAddCmd.Flags().StringVar(&forgeType, "forge-type", string(params.GithubEndpointType), "The forge type of the repository. Supported values: github, gitea.") repoAddCmd.Flags().StringVar(&repoWebhookSecret, "webhook-secret", "", "The webhook secret for this repository") repoAddCmd.Flags().StringVar(&repoCreds, "credentials", "", "Credentials name. See credentials list.") repoAddCmd.Flags().BoolVar(&randomWebhookSecret, "random-webhook-secret", false, "Generate a random webhook secret for this repository.") @@ -360,7 +363,7 @@ func formatRepositories(repos []params.Repository) { } t.AppendHeader(header) for _, val := range repos { - row := table.Row{val.ID, val.Owner, val.Name, val.Endpoint.Name, val.CredentialsName, val.GetBalancerType(), val.PoolManagerStatus.IsRunning} + row := table.Row{val.ID, val.Owner, val.Name, val.Endpoint.Name, val.GetCredentialsName(), val.GetBalancerType(), val.PoolManagerStatus.IsRunning} if long { row = append(row, val.CreatedAt, val.UpdatedAt) } @@ -386,7 +389,7 @@ func formatOneRepository(repo params.Repository) { t.AppendRow(table.Row{"Name", repo.Name}) t.AppendRow(table.Row{"Endpoint", repo.Endpoint.Name}) t.AppendRow(table.Row{"Pool balancer type", repo.GetBalancerType()}) - t.AppendRow(table.Row{"Credentials", repo.CredentialsName}) + t.AppendRow(table.Row{"Credentials", repo.GetCredentialsName()}) t.AppendRow(table.Row{"Pool manager running", repo.PoolManagerStatus.IsRunning}) if !repo.PoolManagerStatus.IsRunning { t.AppendRow(table.Row{"Failure reason", repo.PoolManagerStatus.FailureReason}) diff --git a/cmd/garm/main.go b/cmd/garm/main.go index 20f34eba..f37248d3 100644 --- a/cmd/garm/main.go +++ b/cmd/garm/main.go @@ -384,6 +384,7 @@ func main() { slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to stop provider worker") } + slog.InfoContext(ctx, "shutting down http server") shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 60*time.Second) defer shutdownCancel() if err := srv.Shutdown(shutdownCtx); err != nil { diff --git a/database/common/mocks/Store.go b/database/common/mocks/Store.go index 53b90720..30f1774c 100644 --- a/database/common/mocks/Store.go +++ b/database/common/mocks/Store.go @@ -180,23 +180,79 @@ func (_m *Store) CreateEntityScaleSet(_a0 context.Context, entity params.ForgeEn return r0, r1 } +// CreateGiteaCredentials provides a mock function with given fields: ctx, param +func (_m *Store) CreateGiteaCredentials(ctx context.Context, param params.CreateGiteaCredentialsParams) (params.ForgeCredentials, error) { + ret := _m.Called(ctx, param) + + if len(ret) == 0 { + panic("no return value specified for CreateGiteaCredentials") + } + + var r0 params.ForgeCredentials + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, params.CreateGiteaCredentialsParams) (params.ForgeCredentials, error)); ok { + return rf(ctx, param) + } + if rf, ok := ret.Get(0).(func(context.Context, params.CreateGiteaCredentialsParams) params.ForgeCredentials); ok { + r0 = rf(ctx, param) + } else { + r0 = ret.Get(0).(params.ForgeCredentials) + } + + if rf, ok := ret.Get(1).(func(context.Context, params.CreateGiteaCredentialsParams) error); ok { + r1 = rf(ctx, param) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// CreateGiteaEndpoint provides a mock function with given fields: _a0, param +func (_m *Store) CreateGiteaEndpoint(_a0 context.Context, param params.CreateGiteaEndpointParams) (params.ForgeEndpoint, error) { + ret := _m.Called(_a0, param) + + if len(ret) == 0 { + panic("no return value specified for CreateGiteaEndpoint") + } + + var r0 params.ForgeEndpoint + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, params.CreateGiteaEndpointParams) (params.ForgeEndpoint, error)); ok { + return rf(_a0, param) + } + if rf, ok := ret.Get(0).(func(context.Context, params.CreateGiteaEndpointParams) params.ForgeEndpoint); ok { + r0 = rf(_a0, param) + } else { + r0 = ret.Get(0).(params.ForgeEndpoint) + } + + if rf, ok := ret.Get(1).(func(context.Context, params.CreateGiteaEndpointParams) error); ok { + r1 = rf(_a0, param) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // CreateGithubCredentials provides a mock function with given fields: ctx, param -func (_m *Store) CreateGithubCredentials(ctx context.Context, param params.CreateGithubCredentialsParams) (params.GithubCredentials, error) { +func (_m *Store) CreateGithubCredentials(ctx context.Context, param params.CreateGithubCredentialsParams) (params.ForgeCredentials, error) { ret := _m.Called(ctx, param) if len(ret) == 0 { panic("no return value specified for CreateGithubCredentials") } - var r0 params.GithubCredentials + var r0 params.ForgeCredentials var r1 error - if rf, ok := ret.Get(0).(func(context.Context, params.CreateGithubCredentialsParams) (params.GithubCredentials, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, params.CreateGithubCredentialsParams) (params.ForgeCredentials, error)); ok { return rf(ctx, param) } - if rf, ok := ret.Get(0).(func(context.Context, params.CreateGithubCredentialsParams) params.GithubCredentials); ok { + if rf, ok := ret.Get(0).(func(context.Context, params.CreateGithubCredentialsParams) params.ForgeCredentials); ok { r0 = rf(ctx, param) } else { - r0 = ret.Get(0).(params.GithubCredentials) + r0 = ret.Get(0).(params.ForgeCredentials) } if rf, ok := ret.Get(1).(func(context.Context, params.CreateGithubCredentialsParams) error); ok { @@ -320,9 +376,9 @@ func (_m *Store) CreateOrganization(ctx context.Context, name string, credential return r0, r1 } -// CreateRepository provides a mock function with given fields: ctx, owner, name, credentialsName, webhookSecret, poolBalancerType -func (_m *Store) CreateRepository(ctx context.Context, owner string, name string, credentialsName string, webhookSecret string, poolBalancerType params.PoolBalancerType) (params.Repository, error) { - ret := _m.Called(ctx, owner, name, credentialsName, webhookSecret, poolBalancerType) +// CreateRepository provides a mock function with given fields: ctx, owner, name, credentials, webhookSecret, poolBalancerType +func (_m *Store) CreateRepository(ctx context.Context, owner string, name string, credentials params.ForgeCredentials, webhookSecret string, poolBalancerType params.PoolBalancerType) (params.Repository, error) { + ret := _m.Called(ctx, owner, name, credentials, webhookSecret, poolBalancerType) if len(ret) == 0 { panic("no return value specified for CreateRepository") @@ -330,17 +386,17 @@ func (_m *Store) CreateRepository(ctx context.Context, owner string, name string var r0 params.Repository var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string, string, string, string, params.PoolBalancerType) (params.Repository, error)); ok { - return rf(ctx, owner, name, credentialsName, webhookSecret, poolBalancerType) + if rf, ok := ret.Get(0).(func(context.Context, string, string, params.ForgeCredentials, string, params.PoolBalancerType) (params.Repository, error)); ok { + return rf(ctx, owner, name, credentials, webhookSecret, poolBalancerType) } - if rf, ok := ret.Get(0).(func(context.Context, string, string, string, string, params.PoolBalancerType) params.Repository); ok { - r0 = rf(ctx, owner, name, credentialsName, webhookSecret, poolBalancerType) + if rf, ok := ret.Get(0).(func(context.Context, string, string, params.ForgeCredentials, string, params.PoolBalancerType) params.Repository); ok { + r0 = rf(ctx, owner, name, credentials, webhookSecret, poolBalancerType) } else { r0 = ret.Get(0).(params.Repository) } - if rf, ok := ret.Get(1).(func(context.Context, string, string, string, string, params.PoolBalancerType) error); ok { - r1 = rf(ctx, owner, name, credentialsName, webhookSecret, poolBalancerType) + if rf, ok := ret.Get(1).(func(context.Context, string, string, params.ForgeCredentials, string, params.PoolBalancerType) error); ok { + r1 = rf(ctx, owner, name, credentials, webhookSecret, poolBalancerType) } else { r1 = ret.Error(1) } @@ -458,6 +514,42 @@ func (_m *Store) DeleteEntityPool(ctx context.Context, entity params.ForgeEntity return r0 } +// DeleteGiteaCredentials provides a mock function with given fields: ctx, id +func (_m *Store) DeleteGiteaCredentials(ctx context.Context, id uint) error { + ret := _m.Called(ctx, id) + + if len(ret) == 0 { + panic("no return value specified for DeleteGiteaCredentials") + } + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, uint) error); ok { + r0 = rf(ctx, id) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// DeleteGiteaEndpoint provides a mock function with given fields: _a0, name +func (_m *Store) DeleteGiteaEndpoint(_a0 context.Context, name string) error { + ret := _m.Called(_a0, name) + + if len(ret) == 0 { + panic("no return value specified for DeleteGiteaEndpoint") + } + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, string) error); ok { + r0 = rf(_a0, name) + } else { + r0 = ret.Error(0) + } + + return r0 +} + // DeleteGithubCredentials provides a mock function with given fields: ctx, id func (_m *Store) DeleteGithubCredentials(ctx context.Context, id uint) error { ret := _m.Called(ctx, id) @@ -762,23 +854,135 @@ func (_m *Store) GetEntityPool(ctx context.Context, entity params.ForgeEntity, p return r0, r1 } +// GetForgeEntity provides a mock function with given fields: _a0, entityType, entityID +func (_m *Store) GetForgeEntity(_a0 context.Context, entityType params.ForgeEntityType, entityID string) (params.ForgeEntity, error) { + ret := _m.Called(_a0, entityType, entityID) + + if len(ret) == 0 { + panic("no return value specified for GetForgeEntity") + } + + var r0 params.ForgeEntity + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, params.ForgeEntityType, string) (params.ForgeEntity, error)); ok { + return rf(_a0, entityType, entityID) + } + if rf, ok := ret.Get(0).(func(context.Context, params.ForgeEntityType, string) params.ForgeEntity); ok { + r0 = rf(_a0, entityType, entityID) + } else { + r0 = ret.Get(0).(params.ForgeEntity) + } + + if rf, ok := ret.Get(1).(func(context.Context, params.ForgeEntityType, string) error); ok { + r1 = rf(_a0, entityType, entityID) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetGiteaCredentials provides a mock function with given fields: ctx, id, detailed +func (_m *Store) GetGiteaCredentials(ctx context.Context, id uint, detailed bool) (params.ForgeCredentials, error) { + ret := _m.Called(ctx, id, detailed) + + if len(ret) == 0 { + panic("no return value specified for GetGiteaCredentials") + } + + var r0 params.ForgeCredentials + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, uint, bool) (params.ForgeCredentials, error)); ok { + return rf(ctx, id, detailed) + } + if rf, ok := ret.Get(0).(func(context.Context, uint, bool) params.ForgeCredentials); ok { + r0 = rf(ctx, id, detailed) + } else { + r0 = ret.Get(0).(params.ForgeCredentials) + } + + if rf, ok := ret.Get(1).(func(context.Context, uint, bool) error); ok { + r1 = rf(ctx, id, detailed) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetGiteaCredentialsByName provides a mock function with given fields: ctx, name, detailed +func (_m *Store) GetGiteaCredentialsByName(ctx context.Context, name string, detailed bool) (params.ForgeCredentials, error) { + ret := _m.Called(ctx, name, detailed) + + if len(ret) == 0 { + panic("no return value specified for GetGiteaCredentialsByName") + } + + var r0 params.ForgeCredentials + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string, bool) (params.ForgeCredentials, error)); ok { + return rf(ctx, name, detailed) + } + if rf, ok := ret.Get(0).(func(context.Context, string, bool) params.ForgeCredentials); ok { + r0 = rf(ctx, name, detailed) + } else { + r0 = ret.Get(0).(params.ForgeCredentials) + } + + if rf, ok := ret.Get(1).(func(context.Context, string, bool) error); ok { + r1 = rf(ctx, name, detailed) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetGiteaEndpoint provides a mock function with given fields: _a0, name +func (_m *Store) GetGiteaEndpoint(_a0 context.Context, name string) (params.ForgeEndpoint, error) { + ret := _m.Called(_a0, name) + + if len(ret) == 0 { + panic("no return value specified for GetGiteaEndpoint") + } + + var r0 params.ForgeEndpoint + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string) (params.ForgeEndpoint, error)); ok { + return rf(_a0, name) + } + if rf, ok := ret.Get(0).(func(context.Context, string) params.ForgeEndpoint); ok { + r0 = rf(_a0, name) + } else { + r0 = ret.Get(0).(params.ForgeEndpoint) + } + + if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { + r1 = rf(_a0, name) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetGithubCredentials provides a mock function with given fields: ctx, id, detailed -func (_m *Store) GetGithubCredentials(ctx context.Context, id uint, detailed bool) (params.GithubCredentials, error) { +func (_m *Store) GetGithubCredentials(ctx context.Context, id uint, detailed bool) (params.ForgeCredentials, error) { ret := _m.Called(ctx, id, detailed) if len(ret) == 0 { panic("no return value specified for GetGithubCredentials") } - var r0 params.GithubCredentials + var r0 params.ForgeCredentials var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint, bool) (params.GithubCredentials, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, uint, bool) (params.ForgeCredentials, error)); ok { return rf(ctx, id, detailed) } - if rf, ok := ret.Get(0).(func(context.Context, uint, bool) params.GithubCredentials); ok { + if rf, ok := ret.Get(0).(func(context.Context, uint, bool) params.ForgeCredentials); ok { r0 = rf(ctx, id, detailed) } else { - r0 = ret.Get(0).(params.GithubCredentials) + r0 = ret.Get(0).(params.ForgeCredentials) } if rf, ok := ret.Get(1).(func(context.Context, uint, bool) error); ok { @@ -791,22 +995,22 @@ func (_m *Store) GetGithubCredentials(ctx context.Context, id uint, detailed boo } // GetGithubCredentialsByName provides a mock function with given fields: ctx, name, detailed -func (_m *Store) GetGithubCredentialsByName(ctx context.Context, name string, detailed bool) (params.GithubCredentials, error) { +func (_m *Store) GetGithubCredentialsByName(ctx context.Context, name string, detailed bool) (params.ForgeCredentials, error) { ret := _m.Called(ctx, name, detailed) if len(ret) == 0 { panic("no return value specified for GetGithubCredentialsByName") } - var r0 params.GithubCredentials + var r0 params.ForgeCredentials var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string, bool) (params.GithubCredentials, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, string, bool) (params.ForgeCredentials, error)); ok { return rf(ctx, name, detailed) } - if rf, ok := ret.Get(0).(func(context.Context, string, bool) params.GithubCredentials); ok { + if rf, ok := ret.Get(0).(func(context.Context, string, bool) params.ForgeCredentials); ok { r0 = rf(ctx, name, detailed) } else { - r0 = ret.Get(0).(params.GithubCredentials) + r0 = ret.Get(0).(params.ForgeCredentials) } if rf, ok := ret.Get(1).(func(context.Context, string, bool) error); ok { @@ -846,34 +1050,6 @@ func (_m *Store) GetGithubEndpoint(ctx context.Context, name string) (params.For return r0, r1 } -// GetForgeEntity provides a mock function with given fields: _a0, entityType, entityID -func (_m *Store) GetForgeEntity(_a0 context.Context, entityType params.ForgeEntityType, entityID string) (params.ForgeEntity, error) { - ret := _m.Called(_a0, entityType, entityID) - - if len(ret) == 0 { - panic("no return value specified for GetForgeEntity") - } - - var r0 params.ForgeEntity - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, params.ForgeEntityType, string) (params.ForgeEntity, error)); ok { - return rf(_a0, entityType, entityID) - } - if rf, ok := ret.Get(0).(func(context.Context, params.ForgeEntityType, string) params.ForgeEntity); ok { - r0 = rf(_a0, entityType, entityID) - } else { - r0 = ret.Get(0).(params.ForgeEntity) - } - - if rf, ok := ret.Get(1).(func(context.Context, params.ForgeEntityType, string) error); ok { - r1 = rf(_a0, entityType, entityID) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - // GetInstanceByName provides a mock function with given fields: ctx, instanceName func (_m *Store) GetInstanceByName(ctx context.Context, instanceName string) (params.Instance, error) { ret := _m.Called(ctx, instanceName) @@ -1498,24 +1674,84 @@ func (_m *Store) ListEntityScaleSets(_a0 context.Context, entity params.ForgeEnt return r0, r1 } +// ListGiteaCredentials provides a mock function with given fields: ctx +func (_m *Store) ListGiteaCredentials(ctx context.Context) ([]params.ForgeCredentials, error) { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for ListGiteaCredentials") + } + + var r0 []params.ForgeCredentials + var r1 error + if rf, ok := ret.Get(0).(func(context.Context) ([]params.ForgeCredentials, error)); ok { + return rf(ctx) + } + if rf, ok := ret.Get(0).(func(context.Context) []params.ForgeCredentials); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]params.ForgeCredentials) + } + } + + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// ListGiteaEndpoints provides a mock function with given fields: _a0 +func (_m *Store) ListGiteaEndpoints(_a0 context.Context) ([]params.ForgeEndpoint, error) { + ret := _m.Called(_a0) + + if len(ret) == 0 { + panic("no return value specified for ListGiteaEndpoints") + } + + var r0 []params.ForgeEndpoint + var r1 error + if rf, ok := ret.Get(0).(func(context.Context) ([]params.ForgeEndpoint, error)); ok { + return rf(_a0) + } + if rf, ok := ret.Get(0).(func(context.Context) []params.ForgeEndpoint); ok { + r0 = rf(_a0) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]params.ForgeEndpoint) + } + } + + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(_a0) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // ListGithubCredentials provides a mock function with given fields: ctx -func (_m *Store) ListGithubCredentials(ctx context.Context) ([]params.GithubCredentials, error) { +func (_m *Store) ListGithubCredentials(ctx context.Context) ([]params.ForgeCredentials, error) { ret := _m.Called(ctx) if len(ret) == 0 { panic("no return value specified for ListGithubCredentials") } - var r0 []params.GithubCredentials + var r0 []params.ForgeCredentials var r1 error - if rf, ok := ret.Get(0).(func(context.Context) ([]params.GithubCredentials, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context) ([]params.ForgeCredentials, error)); ok { return rf(ctx) } - if rf, ok := ret.Get(0).(func(context.Context) []params.GithubCredentials); ok { + if rf, ok := ret.Get(0).(func(context.Context) []params.ForgeCredentials); ok { r0 = rf(ctx) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]params.GithubCredentials) + r0 = ret.Get(0).([]params.ForgeCredentials) } } @@ -1920,23 +2156,79 @@ func (_m *Store) UpdateEntityScaleSet(_a0 context.Context, entity params.ForgeEn return r0, r1 } +// UpdateGiteaCredentials provides a mock function with given fields: ctx, id, param +func (_m *Store) UpdateGiteaCredentials(ctx context.Context, id uint, param params.UpdateGiteaCredentialsParams) (params.ForgeCredentials, error) { + ret := _m.Called(ctx, id, param) + + if len(ret) == 0 { + panic("no return value specified for UpdateGiteaCredentials") + } + + var r0 params.ForgeCredentials + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, uint, params.UpdateGiteaCredentialsParams) (params.ForgeCredentials, error)); ok { + return rf(ctx, id, param) + } + if rf, ok := ret.Get(0).(func(context.Context, uint, params.UpdateGiteaCredentialsParams) params.ForgeCredentials); ok { + r0 = rf(ctx, id, param) + } else { + r0 = ret.Get(0).(params.ForgeCredentials) + } + + if rf, ok := ret.Get(1).(func(context.Context, uint, params.UpdateGiteaCredentialsParams) error); ok { + r1 = rf(ctx, id, param) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// UpdateGiteaEndpoint provides a mock function with given fields: _a0, name, param +func (_m *Store) UpdateGiteaEndpoint(_a0 context.Context, name string, param params.UpdateGiteaEndpointParams) (params.ForgeEndpoint, error) { + ret := _m.Called(_a0, name, param) + + if len(ret) == 0 { + panic("no return value specified for UpdateGiteaEndpoint") + } + + var r0 params.ForgeEndpoint + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string, params.UpdateGiteaEndpointParams) (params.ForgeEndpoint, error)); ok { + return rf(_a0, name, param) + } + if rf, ok := ret.Get(0).(func(context.Context, string, params.UpdateGiteaEndpointParams) params.ForgeEndpoint); ok { + r0 = rf(_a0, name, param) + } else { + r0 = ret.Get(0).(params.ForgeEndpoint) + } + + if rf, ok := ret.Get(1).(func(context.Context, string, params.UpdateGiteaEndpointParams) error); ok { + r1 = rf(_a0, name, param) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // UpdateGithubCredentials provides a mock function with given fields: ctx, id, param -func (_m *Store) UpdateGithubCredentials(ctx context.Context, id uint, param params.UpdateGithubCredentialsParams) (params.GithubCredentials, error) { +func (_m *Store) UpdateGithubCredentials(ctx context.Context, id uint, param params.UpdateGithubCredentialsParams) (params.ForgeCredentials, error) { ret := _m.Called(ctx, id, param) if len(ret) == 0 { panic("no return value specified for UpdateGithubCredentials") } - var r0 params.GithubCredentials + var r0 params.ForgeCredentials var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint, params.UpdateGithubCredentialsParams) (params.GithubCredentials, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, uint, params.UpdateGithubCredentialsParams) (params.ForgeCredentials, error)); ok { return rf(ctx, id, param) } - if rf, ok := ret.Get(0).(func(context.Context, uint, params.UpdateGithubCredentialsParams) params.GithubCredentials); ok { + if rf, ok := ret.Get(0).(func(context.Context, uint, params.UpdateGithubCredentialsParams) params.ForgeCredentials); ok { r0 = rf(ctx, id, param) } else { - r0 = ret.Get(0).(params.GithubCredentials) + r0 = ret.Get(0).(params.ForgeCredentials) } if rf, ok := ret.Get(1).(func(context.Context, uint, params.UpdateGithubCredentialsParams) error); ok { diff --git a/database/common/store.go b/database/common/store.go index e5458eaf..1f5b013b 100644 --- a/database/common/store.go +++ b/database/common/store.go @@ -29,16 +29,16 @@ type GithubEndpointStore interface { } type GithubCredentialsStore interface { - CreateGithubCredentials(ctx context.Context, param params.CreateGithubCredentialsParams) (params.GithubCredentials, error) - GetGithubCredentials(ctx context.Context, id uint, detailed bool) (params.GithubCredentials, error) - GetGithubCredentialsByName(ctx context.Context, name string, detailed bool) (params.GithubCredentials, error) - ListGithubCredentials(ctx context.Context) ([]params.GithubCredentials, error) - UpdateGithubCredentials(ctx context.Context, id uint, param params.UpdateGithubCredentialsParams) (params.GithubCredentials, error) + CreateGithubCredentials(ctx context.Context, param params.CreateGithubCredentialsParams) (params.ForgeCredentials, error) + GetGithubCredentials(ctx context.Context, id uint, detailed bool) (params.ForgeCredentials, error) + GetGithubCredentialsByName(ctx context.Context, name string, detailed bool) (params.ForgeCredentials, error) + ListGithubCredentials(ctx context.Context) ([]params.ForgeCredentials, error) + UpdateGithubCredentials(ctx context.Context, id uint, param params.UpdateGithubCredentialsParams) (params.ForgeCredentials, error) DeleteGithubCredentials(ctx context.Context, id uint) error } type RepoStore interface { - CreateRepository(ctx context.Context, owner, name, credentialsName, webhookSecret string, poolBalancerType params.PoolBalancerType) (params.Repository, error) + CreateRepository(ctx context.Context, owner, name string, credentials params.ForgeCredentials, webhookSecret string, poolBalancerType params.PoolBalancerType) (param params.Repository, err error) GetRepository(ctx context.Context, owner, name, endpointName string) (params.Repository, error) GetRepositoryByID(ctx context.Context, repoID string) (params.Repository, error) ListRepositories(ctx context.Context) ([]params.Repository, error) @@ -152,6 +152,23 @@ type ScaleSetInstanceStore interface { CreateScaleSetInstance(_ context.Context, scaleSetID uint, param params.CreateInstanceParams) (instance params.Instance, err error) } +type GiteaEndpointStore interface { + CreateGiteaEndpoint(_ context.Context, param params.CreateGiteaEndpointParams) (ghEndpoint params.ForgeEndpoint, err error) + ListGiteaEndpoints(_ context.Context) ([]params.ForgeEndpoint, error) + DeleteGiteaEndpoint(_ context.Context, name string) (err error) + GetGiteaEndpoint(_ context.Context, name string) (params.ForgeEndpoint, error) + UpdateGiteaEndpoint(_ context.Context, name string, param params.UpdateGiteaEndpointParams) (ghEndpoint params.ForgeEndpoint, err error) +} + +type GiteaCredentialsStore interface { + CreateGiteaCredentials(ctx context.Context, param params.CreateGiteaCredentialsParams) (gtCreds params.ForgeCredentials, err error) + GetGiteaCredentialsByName(ctx context.Context, name string, detailed bool) (params.ForgeCredentials, error) + GetGiteaCredentials(ctx context.Context, id uint, detailed bool) (params.ForgeCredentials, error) + ListGiteaCredentials(ctx context.Context) ([]params.ForgeCredentials, error) + UpdateGiteaCredentials(ctx context.Context, id uint, param params.UpdateGiteaCredentialsParams) (gtCreds params.ForgeCredentials, err error) + DeleteGiteaCredentials(ctx context.Context, id uint) (err error) +} + //go:generate mockery --name=Store type Store interface { RepoStore @@ -167,6 +184,8 @@ type Store interface { EntityPoolStore ScaleSetsStore ScaleSetInstanceStore + GiteaEndpointStore + GiteaCredentialsStore ControllerInfo() (params.ControllerInfo, error) InitController() (params.ControllerInfo, error) diff --git a/database/common/watcher.go b/database/common/watcher.go index 85df1151..4dc18437 100644 --- a/database/common/watcher.go +++ b/database/common/watcher.go @@ -18,6 +18,7 @@ const ( JobEntityType DatabaseEntityType = "job" ControllerEntityType DatabaseEntityType = "controller" GithubCredentialsEntityType DatabaseEntityType = "github_credentials" // #nosec G101 + GiteaCredentialsEntityType DatabaseEntityType = "gitea_credentials" // #nosec G101 GithubEndpointEntityType DatabaseEntityType = "github_endpoint" ScaleSetEntityType DatabaseEntityType = "scaleset" ) diff --git a/database/sql/enterprise.go b/database/sql/enterprise.go index 414a7aaf..26406ac5 100644 --- a/database/sql/enterprise.go +++ b/database/sql/enterprise.go @@ -45,7 +45,6 @@ func (s *sqlDatabase) CreateEnterprise(ctx context.Context, name, credentialsNam newEnterprise := Enterprise{ Name: name, WebhookSecret: secret, - CredentialsName: credentialsName, PoolBalancerType: poolBalancerType, } err = s.conn.Transaction(func(tx *gorm.DB) error { @@ -57,7 +56,6 @@ func (s *sqlDatabase) CreateEnterprise(ctx context.Context, name, credentialsNam return errors.Wrap(runnerErrors.ErrUnprocessable, "credentials have no endpoint") } newEnterprise.CredentialsID = &creds.ID - newEnterprise.CredentialsName = creds.Name newEnterprise.EndpointName = creds.EndpointName q := tx.Create(&newEnterprise) diff --git a/database/sql/enterprise_test.go b/database/sql/enterprise_test.go index 3e8f6493..4971f78f 100644 --- a/database/sql/enterprise_test.go +++ b/database/sql/enterprise_test.go @@ -53,8 +53,8 @@ type EnterpriseTestSuite struct { adminCtx context.Context adminUserID string - testCreds params.GithubCredentials - secondaryTestCreds params.GithubCredentials + testCreds params.ForgeCredentials + secondaryTestCreds params.ForgeCredentials githubEndpoint params.ForgeEndpoint } diff --git a/database/sql/gitea.go b/database/sql/gitea.go new file mode 100644 index 00000000..5ce46663 --- /dev/null +++ b/database/sql/gitea.go @@ -0,0 +1,469 @@ +package sql + +import ( + "context" + "log/slog" + + runnerErrors "github.com/cloudbase/garm-provider-common/errors" + "github.com/cloudbase/garm/auth" + "github.com/cloudbase/garm/database/common" + "github.com/cloudbase/garm/params" + "github.com/pkg/errors" + "gorm.io/gorm" +) + +func (s *sqlDatabase) CreateGiteaEndpoint(_ context.Context, param params.CreateGiteaEndpointParams) (ghEndpoint params.ForgeEndpoint, err error) { + defer func() { + if err == nil { + s.sendNotify(common.GithubEndpointEntityType, common.CreateOperation, ghEndpoint) + } + }() + var endpoint GithubEndpoint + err = s.conn.Transaction(func(tx *gorm.DB) error { + if err := tx.Where("name = ?", param.Name).First(&endpoint).Error; err == nil { + return errors.Wrap(runnerErrors.ErrDuplicateEntity, "github endpoint already exists") + } + endpoint = GithubEndpoint{ + Name: param.Name, + Description: param.Description, + APIBaseURL: param.APIBaseURL, + BaseURL: param.BaseURL, + CACertBundle: param.CACertBundle, + EndpointType: params.GiteaEndpointType, + } + + if err := tx.Create(&endpoint).Error; err != nil { + return errors.Wrap(err, "creating github endpoint") + } + return nil + }) + if err != nil { + return params.ForgeEndpoint{}, errors.Wrap(err, "creating github endpoint") + } + ghEndpoint, err = s.sqlToCommonGithubEndpoint(endpoint) + if err != nil { + return params.ForgeEndpoint{}, errors.Wrap(err, "converting github endpoint") + } + return ghEndpoint, nil +} + +func (s *sqlDatabase) ListGiteaEndpoints(_ context.Context) ([]params.ForgeEndpoint, error) { + var endpoints []GithubEndpoint + err := s.conn.Where("endpoint_type = ?", params.GiteaEndpointType).Find(&endpoints).Error + if err != nil { + return nil, errors.Wrap(err, "fetching github endpoints") + } + + var ret []params.ForgeEndpoint + for _, ep := range endpoints { + commonEp, err := s.sqlToCommonGithubEndpoint(ep) + if err != nil { + return nil, errors.Wrap(err, "converting github endpoint") + } + ret = append(ret, commonEp) + } + return ret, nil +} + +func (s *sqlDatabase) UpdateGiteaEndpoint(_ context.Context, name string, param params.UpdateGiteaEndpointParams) (ghEndpoint params.ForgeEndpoint, err error) { + if name == defaultGithubEndpoint { + return params.ForgeEndpoint{}, runnerErrors.NewBadRequestError("cannot update default endpoint %s", defaultGithubEndpoint) + } + + defer func() { + if err == nil { + s.sendNotify(common.GithubEndpointEntityType, common.UpdateOperation, ghEndpoint) + } + }() + var endpoint GithubEndpoint + err = s.conn.Transaction(func(tx *gorm.DB) error { + if err := tx.Where("name = ? and endpoint_type = ?", name, params.GiteaEndpointType).First(&endpoint).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return errors.Wrap(runnerErrors.ErrNotFound, "gitea endpoint not found") + } + return errors.Wrap(err, "fetching gitea endpoint") + } + if param.APIBaseURL != nil { + endpoint.APIBaseURL = *param.APIBaseURL + } + + if param.BaseURL != nil { + endpoint.BaseURL = *param.BaseURL + } + + if param.CACertBundle != nil { + endpoint.CACertBundle = param.CACertBundle + } + + if param.Description != nil { + endpoint.Description = *param.Description + } + + if err := tx.Save(&endpoint).Error; err != nil { + return errors.Wrap(err, "updating gitea endpoint") + } + + return nil + }) + if err != nil { + return params.ForgeEndpoint{}, errors.Wrap(err, "updating gitea endpoint") + } + ghEndpoint, err = s.sqlToCommonGithubEndpoint(endpoint) + if err != nil { + return params.ForgeEndpoint{}, errors.Wrap(err, "converting gitea endpoint") + } + return ghEndpoint, nil +} + +func (s *sqlDatabase) GetGiteaEndpoint(_ context.Context, name string) (params.ForgeEndpoint, error) { + var endpoint GithubEndpoint + + err := s.conn.Where("name = ? and endpoint_type = ?", name, params.GiteaEndpointType).First(&endpoint).Error + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return params.ForgeEndpoint{}, errors.Wrap(runnerErrors.ErrNotFound, "gitea endpoint not found") + } + return params.ForgeEndpoint{}, errors.Wrap(err, "fetching gitea endpoint") + } + + return s.sqlToCommonGithubEndpoint(endpoint) +} + +func (s *sqlDatabase) DeleteGiteaEndpoint(_ context.Context, name string) (err error) { + if name == defaultGithubEndpoint { + return runnerErrors.NewBadRequestError("cannot delete default endpoint %s", defaultGithubEndpoint) + } + + defer func() { + if err == nil { + s.sendNotify(common.GithubEndpointEntityType, common.DeleteOperation, params.ForgeEndpoint{Name: name}) + } + }() + err = s.conn.Transaction(func(tx *gorm.DB) error { + var endpoint GithubEndpoint + if err := tx.Where("name = ? and endpoint_type = ?", name, params.GiteaEndpointType).First(&endpoint).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil + } + return errors.Wrap(err, "fetching gitea endpoint") + } + + var credsCount int64 + if err := tx.Model(&GithubCredentials{}).Where("endpoint_name = ?", endpoint.Name).Count(&credsCount).Error; err != nil { + if !errors.Is(err, gorm.ErrRecordNotFound) { + return errors.Wrap(err, "fetching gitea credentials") + } + } + + var repoCnt int64 + if err := tx.Model(&Repository{}).Where("endpoint_name = ?", endpoint.Name).Count(&repoCnt).Error; err != nil { + if !errors.Is(err, gorm.ErrRecordNotFound) { + return errors.Wrap(err, "fetching gitea repositories") + } + } + + var orgCnt int64 + if err := tx.Model(&Organization{}).Where("endpoint_name = ?", endpoint.Name).Count(&orgCnt).Error; err != nil { + if !errors.Is(err, gorm.ErrRecordNotFound) { + return errors.Wrap(err, "fetching gitea organizations") + } + } + + var entCnt int64 + if err := tx.Model(&Enterprise{}).Where("endpoint_name = ?", endpoint.Name).Count(&entCnt).Error; err != nil { + if !errors.Is(err, gorm.ErrRecordNotFound) { + return errors.Wrap(err, "fetching gitea enterprises") + } + } + + if credsCount > 0 || repoCnt > 0 || orgCnt > 0 || entCnt > 0 { + return errors.New("cannot delete endpoint with associated entities") + } + + if err := tx.Unscoped().Delete(&endpoint).Error; err != nil { + return errors.Wrap(err, "deleting gitea endpoint") + } + return nil + }) + if err != nil { + return errors.Wrap(err, "deleting gitea endpoint") + } + return nil +} + +func (s *sqlDatabase) CreateGiteaCredentials(ctx context.Context, param params.CreateGiteaCredentialsParams) (gtCreds params.ForgeCredentials, err error) { + userID, err := getUIDFromContext(ctx) + if err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "creating github credentials") + } + if param.Endpoint == "" { + return params.ForgeCredentials{}, errors.Wrap(runnerErrors.ErrBadRequest, "endpoint name is required") + } + + defer func() { + if err == nil { + s.sendNotify(common.GiteaCredentialsEntityType, common.CreateOperation, gtCreds) + } + }() + var creds GiteaCredentials + err = s.conn.Transaction(func(tx *gorm.DB) error { + var endpoint GithubEndpoint + if err := tx.Where("name = ? and endpoint_type = ?", param.Endpoint, params.GiteaEndpointType).First(&endpoint).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return errors.Wrap(runnerErrors.ErrNotFound, "github endpoint not found") + } + return errors.Wrap(err, "fetching github endpoint") + } + + if err := tx.Where("name = ? and user_id = ?", param.Name, userID).First(&creds).Error; err == nil { + return errors.Wrap(runnerErrors.ErrDuplicateEntity, "github credentials already exists") + } + + var data []byte + var err error + switch param.AuthType { + case params.ForgeAuthTypePAT: + data, err = s.marshalAndSeal(param.PAT) + case params.ForgeAuthTypeApp: + data, err = s.marshalAndSeal(param.App) + default: + return errors.Wrap(runnerErrors.ErrBadRequest, "invalid auth type") + } + if err != nil { + return errors.Wrap(err, "marshaling and sealing credentials") + } + + creds = GiteaCredentials{ + Name: param.Name, + Description: param.Description, + EndpointName: &endpoint.Name, + AuthType: param.AuthType, + Payload: data, + UserID: &userID, + } + + if err := tx.Create(&creds).Error; err != nil { + return errors.Wrap(err, "creating github credentials") + } + // Skip making an extra query. + creds.Endpoint = endpoint + + return nil + }) + if err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "creating github credentials") + } + gtCreds, err = s.sqlGiteaToCommonForgeCredentials(creds) + if err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "converting github credentials") + } + return gtCreds, nil +} + +func (s *sqlDatabase) getGiteaCredentialsByName(ctx context.Context, tx *gorm.DB, name string, detailed bool) (GiteaCredentials, error) { + var creds GiteaCredentials + q := tx.Preload("Endpoint") + + if detailed { + q = q. + Preload("Repositories"). + Preload("Organizations") + } + + userID, err := getUIDFromContext(ctx) + if err != nil { + return GiteaCredentials{}, errors.Wrap(err, "fetching gitea credentials") + } + q = q.Where("user_id = ?", userID) + + err = q.Where("name = ?", name).First(&creds).Error + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return GiteaCredentials{}, errors.Wrap(runnerErrors.ErrNotFound, "gitea credentials not found") + } + return GiteaCredentials{}, errors.Wrap(err, "fetching gitea credentials") + } + + return creds, nil +} + +func (s *sqlDatabase) GetGiteaCredentialsByName(ctx context.Context, name string, detailed bool) (params.ForgeCredentials, error) { + creds, err := s.getGiteaCredentialsByName(ctx, s.conn, name, detailed) + if err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "fetching gitea credentials") + } + + return s.sqlGiteaToCommonForgeCredentials(creds) +} + +func (s *sqlDatabase) GetGiteaCredentials(ctx context.Context, id uint, detailed bool) (params.ForgeCredentials, error) { + var creds GiteaCredentials + q := s.conn.Preload("Endpoint") + + if detailed { + q = q. + Preload("Repositories"). + Preload("Organizations") + } + + if !auth.IsAdmin(ctx) { + userID, err := getUIDFromContext(ctx) + if err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "fetching gitea credentials") + } + q = q.Where("user_id = ?", userID) + } + + err := q.Where("id = ?", id).First(&creds).Error + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return params.ForgeCredentials{}, errors.Wrap(runnerErrors.ErrNotFound, "gitea credentials not found") + } + return params.ForgeCredentials{}, errors.Wrap(err, "fetching gitea credentials") + } + + return s.sqlGiteaToCommonForgeCredentials(creds) +} + +func (s *sqlDatabase) ListGiteaCredentials(ctx context.Context) ([]params.ForgeCredentials, error) { + q := s.conn.Preload("Endpoint") + if !auth.IsAdmin(ctx) { + userID, err := getUIDFromContext(ctx) + if err != nil { + return nil, errors.Wrap(err, "fetching gitea credentials") + } + q = q.Where("user_id = ?", userID) + } + + var creds []GiteaCredentials + err := q.Preload("Endpoint").Find(&creds).Error + if err != nil { + return nil, errors.Wrap(err, "fetching gitea credentials") + } + + var ret []params.ForgeCredentials + for _, c := range creds { + commonCreds, err := s.sqlGiteaToCommonForgeCredentials(c) + if err != nil { + return nil, errors.Wrap(err, "converting gitea credentials") + } + ret = append(ret, commonCreds) + } + return ret, nil +} + +func (s *sqlDatabase) UpdateGiteaCredentials(ctx context.Context, id uint, param params.UpdateGiteaCredentialsParams) (gtCreds params.ForgeCredentials, err error) { + defer func() { + if err == nil { + s.sendNotify(common.GiteaCredentialsEntityType, common.UpdateOperation, gtCreds) + } + }() + var creds GiteaCredentials + err = s.conn.Transaction(func(tx *gorm.DB) error { + q := tx.Preload("Endpoint") + if !auth.IsAdmin(ctx) { + userID, err := getUIDFromContext(ctx) + if err != nil { + return errors.Wrap(err, "updating gitea credentials") + } + q = q.Where("user_id = ?", userID) + } + + if err := q.Where("id = ?", id).First(&creds).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return errors.Wrap(runnerErrors.ErrNotFound, "gitea credentials not found") + } + return errors.Wrap(err, "fetching gitea credentials") + } + + if param.Name != nil { + creds.Name = *param.Name + } + if param.Description != nil { + creds.Description = *param.Description + } + + var data []byte + var err error + switch creds.AuthType { + case params.ForgeAuthTypePAT: + if param.PAT != nil { + data, err = s.marshalAndSeal(param.PAT) + } + default: + return errors.Wrap(runnerErrors.ErrBadRequest, "invalid auth type") + } + + if err != nil { + return errors.Wrap(err, "marshaling and sealing credentials") + } + if len(data) > 0 { + creds.Payload = data + } + + if err := tx.Save(&creds).Error; err != nil { + return errors.Wrap(err, "updating gitea credentials") + } + return nil + }) + if err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "updating gitea credentials") + } + + gtCreds, err = s.sqlGiteaToCommonForgeCredentials(creds) + if err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "converting gitea credentials") + } + return gtCreds, nil +} + +func (s *sqlDatabase) DeleteGiteaCredentials(ctx context.Context, id uint) (err error) { + var creds GiteaCredentials + defer func() { + if err == nil { + forgeCreds, innerErr := s.sqlGiteaToCommonForgeCredentials(creds) + if innerErr != nil { + slog.ErrorContext(ctx, "converting gitea credentials", "error", innerErr) + } + if creds.ID == 0 || creds.Name == "" { + return + } + s.sendNotify(common.GiteaCredentialsEntityType, common.DeleteOperation, forgeCreds) + } + }() + err = s.conn.Transaction(func(tx *gorm.DB) error { + q := tx.Where("id = ?", id). + Preload("Repositories"). + Preload("Organizations") + if !auth.IsAdmin(ctx) { + userID, err := getUIDFromContext(ctx) + if err != nil { + return errors.Wrap(err, "deleting gitea credentials") + } + q = q.Where("user_id = ?", userID) + } + + err := q.First(&creds).Error + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil + } + return errors.Wrap(err, "fetching gitea credentials") + } + + if len(creds.Repositories) > 0 { + return errors.Wrap(runnerErrors.ErrBadRequest, "cannot delete credentials with repositories") + } + if len(creds.Organizations) > 0 { + return errors.Wrap(runnerErrors.ErrBadRequest, "cannot delete credentials with organizations") + } + if err := tx.Unscoped().Delete(&creds).Error; err != nil { + return errors.Wrap(err, "deleting gitea credentials") + } + return nil + }) + if err != nil { + return errors.Wrap(err, "deleting gitea credentials") + } + return nil +} diff --git a/database/sql/github.go b/database/sql/github.go index 861c824c..d2c05244 100644 --- a/database/sql/github.go +++ b/database/sql/github.go @@ -17,12 +17,10 @@ package sql import ( "context" - "github.com/google/uuid" "github.com/pkg/errors" "gorm.io/gorm" runnerErrors "github.com/cloudbase/garm-provider-common/errors" - "github.com/cloudbase/garm-provider-common/util" "github.com/cloudbase/garm/auth" "github.com/cloudbase/garm/database/common" "github.com/cloudbase/garm/params" @@ -32,89 +30,6 @@ const ( defaultGithubEndpoint string = "github.com" ) -func (s *sqlDatabase) sqlToCommonGithubCredentials(creds GithubCredentials) (params.GithubCredentials, error) { - if len(creds.Payload) == 0 { - return params.GithubCredentials{}, errors.New("empty credentials payload") - } - data, err := util.Unseal(creds.Payload, []byte(s.cfg.Passphrase)) - if err != nil { - return params.GithubCredentials{}, errors.Wrap(err, "unsealing credentials") - } - - ep, err := s.sqlToCommonGithubEndpoint(creds.Endpoint) - if err != nil { - return params.GithubCredentials{}, errors.Wrap(err, "converting github endpoint") - } - - commonCreds := params.GithubCredentials{ - ID: creds.ID, - Name: creds.Name, - Description: creds.Description, - APIBaseURL: creds.Endpoint.APIBaseURL, - BaseURL: creds.Endpoint.BaseURL, - UploadBaseURL: creds.Endpoint.UploadBaseURL, - CABundle: creds.Endpoint.CACertBundle, - AuthType: creds.AuthType, - CreatedAt: creds.CreatedAt, - UpdatedAt: creds.UpdatedAt, - Endpoint: ep, - CredentialsPayload: data, - } - - for _, repo := range creds.Repositories { - commonRepo, err := s.sqlToCommonRepository(repo, false) - if err != nil { - return params.GithubCredentials{}, errors.Wrap(err, "converting github repository") - } - commonCreds.Repositories = append(commonCreds.Repositories, commonRepo) - } - - for _, org := range creds.Organizations { - commonOrg, err := s.sqlToCommonOrganization(org, false) - if err != nil { - return params.GithubCredentials{}, errors.Wrap(err, "converting github organization") - } - commonCreds.Organizations = append(commonCreds.Organizations, commonOrg) - } - - for _, ent := range creds.Enterprises { - commonEnt, err := s.sqlToCommonEnterprise(ent, false) - if err != nil { - return params.GithubCredentials{}, errors.Wrapf(err, "converting github enterprise: %s", ent.Name) - } - commonCreds.Enterprises = append(commonCreds.Enterprises, commonEnt) - } - - return commonCreds, nil -} - -func (s *sqlDatabase) sqlToCommonGithubEndpoint(ep GithubEndpoint) (params.ForgeEndpoint, error) { - return params.ForgeEndpoint{ - Name: ep.Name, - Description: ep.Description, - APIBaseURL: ep.APIBaseURL, - BaseURL: ep.BaseURL, - UploadBaseURL: ep.UploadBaseURL, - CACertBundle: ep.CACertBundle, - CreatedAt: ep.CreatedAt, - EndpointType: ep.EndpointType, - UpdatedAt: ep.UpdatedAt, - }, nil -} - -func getUIDFromContext(ctx context.Context) (uuid.UUID, error) { - userID := auth.UserID(ctx) - if userID == "" { - return uuid.Nil, errors.Wrap(runnerErrors.ErrUnauthorized, "getting UID from context") - } - - asUUID, err := uuid.Parse(userID) - if err != nil { - return uuid.Nil, errors.Wrap(runnerErrors.ErrUnauthorized, "parsing UID from context") - } - return asUUID, nil -} - func (s *sqlDatabase) CreateGithubEndpoint(_ context.Context, param params.CreateGithubEndpointParams) (ghEndpoint params.ForgeEndpoint, err error) { defer func() { if err == nil { @@ -133,6 +48,7 @@ func (s *sqlDatabase) CreateGithubEndpoint(_ context.Context, param params.Creat BaseURL: param.BaseURL, UploadBaseURL: param.UploadBaseURL, CACertBundle: param.CACertBundle, + EndpointType: params.GithubEndpointType, } if err := tx.Create(&endpoint).Error; err != nil { @@ -152,7 +68,7 @@ func (s *sqlDatabase) CreateGithubEndpoint(_ context.Context, param params.Creat func (s *sqlDatabase) ListGithubEndpoints(_ context.Context) ([]params.ForgeEndpoint, error) { var endpoints []GithubEndpoint - err := s.conn.Find(&endpoints).Error + err := s.conn.Where("endpoint_type = ?", params.GithubEndpointType).Find(&endpoints).Error if err != nil { return nil, errors.Wrap(err, "fetching github endpoints") } @@ -180,7 +96,7 @@ func (s *sqlDatabase) UpdateGithubEndpoint(_ context.Context, name string, param }() var endpoint GithubEndpoint err = s.conn.Transaction(func(tx *gorm.DB) error { - if err := tx.Where("name = ?", name).First(&endpoint).Error; err != nil { + if err := tx.Where("name = ? and endpoint_type = ?", name, params.GithubEndpointType).First(&endpoint).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return errors.Wrap(runnerErrors.ErrNotFound, "github endpoint not found") } @@ -225,7 +141,7 @@ func (s *sqlDatabase) UpdateGithubEndpoint(_ context.Context, name string, param func (s *sqlDatabase) GetGithubEndpoint(_ context.Context, name string) (params.ForgeEndpoint, error) { var endpoint GithubEndpoint - err := s.conn.Where("name = ?", name).First(&endpoint).Error + err := s.conn.Where("name = ? and endpoint_type = ?", name, params.GithubEndpointType).First(&endpoint).Error if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return params.ForgeEndpoint{}, errors.Wrap(runnerErrors.ErrNotFound, "github endpoint not found") @@ -248,7 +164,7 @@ func (s *sqlDatabase) DeleteGithubEndpoint(_ context.Context, name string) (err }() err = s.conn.Transaction(func(tx *gorm.DB) error { var endpoint GithubEndpoint - if err := tx.Where("name = ?", name).First(&endpoint).Error; err != nil { + if err := tx.Where("name = ? and endpoint_type = ?", name, params.GithubEndpointType).First(&endpoint).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil } @@ -298,13 +214,13 @@ func (s *sqlDatabase) DeleteGithubEndpoint(_ context.Context, name string) (err return nil } -func (s *sqlDatabase) CreateGithubCredentials(ctx context.Context, param params.CreateGithubCredentialsParams) (ghCreds params.GithubCredentials, err error) { +func (s *sqlDatabase) CreateGithubCredentials(ctx context.Context, param params.CreateGithubCredentialsParams) (ghCreds params.ForgeCredentials, err error) { userID, err := getUIDFromContext(ctx) if err != nil { - return params.GithubCredentials{}, errors.Wrap(err, "creating github credentials") + return params.ForgeCredentials{}, errors.Wrap(err, "creating github credentials") } if param.Endpoint == "" { - return params.GithubCredentials{}, errors.Wrap(runnerErrors.ErrBadRequest, "endpoint name is required") + return params.ForgeCredentials{}, errors.Wrap(runnerErrors.ErrBadRequest, "endpoint name is required") } defer func() { @@ -315,7 +231,7 @@ func (s *sqlDatabase) CreateGithubCredentials(ctx context.Context, param params. var creds GithubCredentials err = s.conn.Transaction(func(tx *gorm.DB) error { var endpoint GithubEndpoint - if err := tx.Where("name = ?", param.Endpoint).First(&endpoint).Error; err != nil { + if err := tx.Where("name = ? and endpoint_type = ?", param.Endpoint, params.GithubEndpointType).First(&endpoint).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return errors.Wrap(runnerErrors.ErrNotFound, "github endpoint not found") } @@ -358,11 +274,11 @@ func (s *sqlDatabase) CreateGithubCredentials(ctx context.Context, param params. return nil }) if err != nil { - return params.GithubCredentials{}, errors.Wrap(err, "creating github credentials") + return params.ForgeCredentials{}, errors.Wrap(err, "creating github credentials") } - ghCreds, err = s.sqlToCommonGithubCredentials(creds) + ghCreds, err = s.sqlToCommonForgeCredentials(creds) if err != nil { - return params.GithubCredentials{}, errors.Wrap(err, "converting github credentials") + return params.ForgeCredentials{}, errors.Wrap(err, "converting github credentials") } return ghCreds, nil } @@ -395,16 +311,16 @@ func (s *sqlDatabase) getGithubCredentialsByName(ctx context.Context, tx *gorm.D return creds, nil } -func (s *sqlDatabase) GetGithubCredentialsByName(ctx context.Context, name string, detailed bool) (params.GithubCredentials, error) { +func (s *sqlDatabase) GetGithubCredentialsByName(ctx context.Context, name string, detailed bool) (params.ForgeCredentials, error) { creds, err := s.getGithubCredentialsByName(ctx, s.conn, name, detailed) if err != nil { - return params.GithubCredentials{}, errors.Wrap(err, "fetching github credentials") + return params.ForgeCredentials{}, errors.Wrap(err, "fetching github credentials") } - return s.sqlToCommonGithubCredentials(creds) + return s.sqlToCommonForgeCredentials(creds) } -func (s *sqlDatabase) GetGithubCredentials(ctx context.Context, id uint, detailed bool) (params.GithubCredentials, error) { +func (s *sqlDatabase) GetGithubCredentials(ctx context.Context, id uint, detailed bool) (params.ForgeCredentials, error) { var creds GithubCredentials q := s.conn.Preload("Endpoint") @@ -418,7 +334,7 @@ func (s *sqlDatabase) GetGithubCredentials(ctx context.Context, id uint, detaile if !auth.IsAdmin(ctx) { userID, err := getUIDFromContext(ctx) if err != nil { - return params.GithubCredentials{}, errors.Wrap(err, "fetching github credentials") + return params.ForgeCredentials{}, errors.Wrap(err, "fetching github credentials") } q = q.Where("user_id = ?", userID) } @@ -426,15 +342,15 @@ func (s *sqlDatabase) GetGithubCredentials(ctx context.Context, id uint, detaile err := q.Where("id = ?", id).First(&creds).Error if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - return params.GithubCredentials{}, errors.Wrap(runnerErrors.ErrNotFound, "github credentials not found") + return params.ForgeCredentials{}, errors.Wrap(runnerErrors.ErrNotFound, "github credentials not found") } - return params.GithubCredentials{}, errors.Wrap(err, "fetching github credentials") + return params.ForgeCredentials{}, errors.Wrap(err, "fetching github credentials") } - return s.sqlToCommonGithubCredentials(creds) + return s.sqlToCommonForgeCredentials(creds) } -func (s *sqlDatabase) ListGithubCredentials(ctx context.Context) ([]params.GithubCredentials, error) { +func (s *sqlDatabase) ListGithubCredentials(ctx context.Context) ([]params.ForgeCredentials, error) { q := s.conn.Preload("Endpoint") if !auth.IsAdmin(ctx) { userID, err := getUIDFromContext(ctx) @@ -450,9 +366,9 @@ func (s *sqlDatabase) ListGithubCredentials(ctx context.Context) ([]params.Githu return nil, errors.Wrap(err, "fetching github credentials") } - var ret []params.GithubCredentials + var ret []params.ForgeCredentials for _, c := range creds { - commonCreds, err := s.sqlToCommonGithubCredentials(c) + commonCreds, err := s.sqlToCommonForgeCredentials(c) if err != nil { return nil, errors.Wrap(err, "converting github credentials") } @@ -461,7 +377,7 @@ func (s *sqlDatabase) ListGithubCredentials(ctx context.Context) ([]params.Githu return ret, nil } -func (s *sqlDatabase) UpdateGithubCredentials(ctx context.Context, id uint, param params.UpdateGithubCredentialsParams) (ghCreds params.GithubCredentials, err error) { +func (s *sqlDatabase) UpdateGithubCredentials(ctx context.Context, id uint, param params.UpdateGithubCredentialsParams) (ghCreds params.ForgeCredentials, err error) { defer func() { if err == nil { s.sendNotify(common.GithubCredentialsEntityType, common.UpdateOperation, ghCreds) @@ -530,12 +446,12 @@ func (s *sqlDatabase) UpdateGithubCredentials(ctx context.Context, id uint, para return nil }) if err != nil { - return params.GithubCredentials{}, errors.Wrap(err, "updating github credentials") + return params.ForgeCredentials{}, errors.Wrap(err, "updating github credentials") } - ghCreds, err = s.sqlToCommonGithubCredentials(creds) + ghCreds, err = s.sqlToCommonForgeCredentials(creds) if err != nil { - return params.GithubCredentials{}, errors.Wrap(err, "converting github credentials") + return params.ForgeCredentials{}, errors.Wrap(err, "converting github credentials") } return ghCreds, nil } @@ -544,7 +460,7 @@ func (s *sqlDatabase) DeleteGithubCredentials(ctx context.Context, id uint) (err var name string defer func() { if err == nil { - s.sendNotify(common.GithubCredentialsEntityType, common.DeleteOperation, params.GithubCredentials{ID: id, Name: name}) + s.sendNotify(common.GithubCredentialsEntityType, common.DeleteOperation, params.ForgeCredentials{ID: id, Name: name}) } }() err = s.conn.Transaction(func(tx *gorm.DB) error { diff --git a/database/sql/github_test.go b/database/sql/github_test.go index e46d963d..49de9aa3 100644 --- a/database/sql/github_test.go +++ b/database/sql/github_test.go @@ -533,7 +533,7 @@ func (s *GithubTestSuite) TestDeleteCredentialsFailsIfReposOrgsOrEntitiesUseIt() s.Require().NoError(err) s.Require().NotNil(creds) - repo, err := s.db.CreateRepository(ctx, "test-owner", "test-repo", creds.Name, "superSecret@123BlaBla", params.PoolBalancerTypeRoundRobin) + repo, err := s.db.CreateRepository(ctx, "test-owner", "test-repo", creds, "superSecret@123BlaBla", params.PoolBalancerTypeRoundRobin) s.Require().NoError(err) s.Require().NotNil(repo) diff --git a/database/sql/models.go b/database/sql/models.go index 2accccc4..0ff2d8f4 100644 --- a/database/sql/models.go +++ b/database/sql/models.go @@ -1,17 +1,3 @@ -// Copyright 2022 Cloudbase Solutions SRL -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - package sql import ( @@ -46,6 +32,22 @@ func (b *Base) BeforeCreate(_ *gorm.DB) error { return nil } +type ControllerInfo struct { + Base + + ControllerID uuid.UUID + + CallbackURL string + MetadataURL string + WebhookBaseURL string + // MinimumJobAgeBackoff is the minimum time that a job must be in the queue + // before GARM will attempt to allocate a runner to service it. This backoff + // is useful if you have idle runners in various pools that could potentially + // pick up the job. GARM would allow this amount of time for runners to react + // before spinning up a new one and potentially having to scale down later. + MinimumJobAgeBackoff uint +} + type Tag struct { Base @@ -152,11 +154,12 @@ type RepositoryEvent struct { type Repository struct { Base - CredentialsName string - CredentialsID *uint `gorm:"index"` Credentials GithubCredentials `gorm:"foreignKey:CredentialsID;constraint:OnDelete:SET NULL"` + GiteaCredentialsID *uint `gorm:"index"` + GiteaCredentials GiteaCredentials `gorm:"foreignKey:GiteaCredentialsID;constraint:OnDelete:SET NULL"` + Owner string `gorm:"index:idx_owner_nocase,unique,collate:nocase"` Name string `gorm:"index:idx_owner_nocase,unique,collate:nocase"` WebhookSecret []byte @@ -184,11 +187,12 @@ type OrganizationEvent struct { type Organization struct { Base - CredentialsName string - CredentialsID *uint `gorm:"index"` Credentials GithubCredentials `gorm:"foreignKey:CredentialsID;constraint:OnDelete:SET NULL"` + GiteaCredentialsID *uint `gorm:"index"` + GiteaCredentials GiteaCredentials `gorm:"foreignKey:GiteaCredentialsID;constraint:OnDelete:SET NULL"` + Name string `gorm:"index:idx_org_name_nocase,collate:nocase"` WebhookSecret []byte Pools []Pool `gorm:"foreignKey:OrgID"` @@ -216,8 +220,6 @@ type EnterpriseEvent struct { type Enterprise struct { Base - CredentialsName string - CredentialsID *uint `gorm:"index"` Credentials GithubCredentials `gorm:"foreignKey:CredentialsID;constraint:OnDelete:SET NULL"` @@ -300,22 +302,6 @@ type User struct { Enabled bool } -type ControllerInfo struct { - Base - - ControllerID uuid.UUID - - CallbackURL string - MetadataURL string - WebhookBaseURL string - // MinimumJobAgeBackoff is the minimum time that a job must be in the queue - // before GARM will attempt to allocate a runner to service it. This backoff - // is useful if you have idle runners in various pools that could potentially - // pick up the job. GARM would allow this amount of time for runners to react - // before spinning up a new one and potentially having to scale down later. - MinimumJobAgeBackoff uint -} - type WorkflowJob struct { // ID is the ID of the job. ID int64 `gorm:"index"` @@ -381,7 +367,7 @@ type GithubEndpoint struct { UpdatedAt time.Time DeletedAt gorm.DeletedAt `gorm:"index"` - EndpointType params.EndpointType + EndpointType params.EndpointType `gorm:"index:idx_endpoint_type"` Description string `gorm:"type:text"` APIBaseURL string `gorm:"type:text collate nocase"` @@ -408,3 +394,21 @@ type GithubCredentials struct { Organizations []Organization `gorm:"foreignKey:CredentialsID"` Enterprises []Enterprise `gorm:"foreignKey:CredentialsID"` } + +type GiteaCredentials struct { + gorm.Model + + Name string `gorm:"index:idx_gitea_credentials,unique;type:varchar(64) collate nocase"` + UserID *uuid.UUID `gorm:"index:idx_gitea_credentials,unique"` + User User `gorm:"foreignKey:UserID"` + + Description string `gorm:"type:text"` + AuthType params.ForgeAuthType `gorm:"index"` + Payload []byte `gorm:"type:longblob"` + + Endpoint GithubEndpoint `gorm:"foreignKey:EndpointName"` + EndpointName *string `gorm:"index"` + + Repositories []Repository `gorm:"foreignKey:GiteaCredentialsID"` + Organizations []Organization `gorm:"foreignKey:GiteaCredentialsID"` +} diff --git a/database/sql/organizations.go b/database/sql/organizations.go index 07ce32d8..bf270445 100644 --- a/database/sql/organizations.go +++ b/database/sql/organizations.go @@ -46,7 +46,6 @@ func (s *sqlDatabase) CreateOrganization(ctx context.Context, name, credentialsN newOrg := Organization{ Name: name, WebhookSecret: secret, - CredentialsName: credentialsName, PoolBalancerType: poolBalancerType, } @@ -59,7 +58,6 @@ func (s *sqlDatabase) CreateOrganization(ctx context.Context, name, credentialsN return errors.Wrap(runnerErrors.ErrUnprocessable, "credentials have no endpoint") } newOrg.CredentialsID = &creds.ID - newOrg.CredentialsName = creds.Name newOrg.EndpointName = creds.EndpointName q := tx.Create(&newOrg) @@ -166,7 +164,6 @@ func (s *sqlDatabase) UpdateOrganization(ctx context.Context, orgID string, para } if param.CredentialsName != "" { - org.CredentialsName = param.CredentialsName creds, err = s.getGithubCredentialsByName(ctx, tx, param.CredentialsName, false) if err != nil { return errors.Wrap(err, "fetching credentials") diff --git a/database/sql/organizations_test.go b/database/sql/organizations_test.go index 030a3abe..a7ad23b4 100644 --- a/database/sql/organizations_test.go +++ b/database/sql/organizations_test.go @@ -53,8 +53,8 @@ type OrgTestSuite struct { adminCtx context.Context adminUserID string - testCreds params.GithubCredentials - secondaryTestCreds params.GithubCredentials + testCreds params.ForgeCredentials + secondaryTestCreds params.ForgeCredentials githubEndpoint params.ForgeEndpoint } diff --git a/database/sql/pools_test.go b/database/sql/pools_test.go index 758dcacd..dfb82510 100644 --- a/database/sql/pools_test.go +++ b/database/sql/pools_test.go @@ -211,7 +211,7 @@ func (s *PoolsTestSuite) TestEntityPoolOperations() { ep := garmTesting.CreateDefaultGithubEndpoint(s.ctx, s.Store, s.T()) creds := garmTesting.CreateTestGithubCredentials(s.ctx, "test-creds", s.Store, s.T(), ep) s.T().Cleanup(func() { s.Store.DeleteGithubCredentials(s.ctx, creds.ID) }) - repo, err := s.Store.CreateRepository(s.ctx, "test-owner", "test-repo", creds.Name, "test-secret", params.PoolBalancerTypeRoundRobin) + repo, err := s.Store.CreateRepository(s.ctx, "test-owner", "test-repo", creds, "test-secret", params.PoolBalancerTypeRoundRobin) s.Require().NoError(err) s.Require().NotEmpty(repo.ID) s.T().Cleanup(func() { s.Store.DeleteRepository(s.ctx, repo.ID) }) @@ -291,7 +291,7 @@ func (s *PoolsTestSuite) TestListEntityInstances() { ep := garmTesting.CreateDefaultGithubEndpoint(s.ctx, s.Store, s.T()) creds := garmTesting.CreateTestGithubCredentials(s.ctx, "test-creds", s.Store, s.T(), ep) s.T().Cleanup(func() { s.Store.DeleteGithubCredentials(s.ctx, creds.ID) }) - repo, err := s.Store.CreateRepository(s.ctx, "test-owner", "test-repo", creds.Name, "test-secret", params.PoolBalancerTypeRoundRobin) + repo, err := s.Store.CreateRepository(s.ctx, "test-owner", "test-repo", creds, "test-secret", params.PoolBalancerTypeRoundRobin) s.Require().NoError(err) s.Require().NotEmpty(repo.ID) s.T().Cleanup(func() { s.Store.DeleteRepository(s.ctx, repo.ID) }) diff --git a/database/sql/repositories.go b/database/sql/repositories.go index 6b744163..d7419070 100644 --- a/database/sql/repositories.go +++ b/database/sql/repositories.go @@ -29,7 +29,7 @@ import ( "github.com/cloudbase/garm/params" ) -func (s *sqlDatabase) CreateRepository(ctx context.Context, owner, name, credentialsName, webhookSecret string, poolBalancerType params.PoolBalancerType) (param params.Repository, err error) { +func (s *sqlDatabase) CreateRepository(ctx context.Context, owner, name string, credentials params.ForgeCredentials, webhookSecret string, poolBalancerType params.PoolBalancerType) (param params.Repository, err error) { defer func() { if err == nil { s.sendNotify(common.RepositoryEntityType, common.CreateOperation, param) @@ -51,32 +51,32 @@ func (s *sqlDatabase) CreateRepository(ctx context.Context, owner, name, credent PoolBalancerType: poolBalancerType, } err = s.conn.Transaction(func(tx *gorm.DB) error { - creds, err := s.getGithubCredentialsByName(ctx, tx, credentialsName, false) - if err != nil { - return errors.Wrap(err, "creating repository") + switch credentials.ForgeType { + case params.GithubEndpointType: + newRepo.CredentialsID = &credentials.ID + case params.GiteaEndpointType: + newRepo.GiteaCredentialsID = &credentials.ID + default: + return errors.Wrap(runnerErrors.ErrBadRequest, "unsupported credentials type") } - if creds.EndpointName == nil { - return errors.Wrap(runnerErrors.ErrUnprocessable, "credentials have no endpoint") - } - newRepo.CredentialsID = &creds.ID - newRepo.CredentialsName = creds.Name - newRepo.EndpointName = creds.EndpointName + newRepo.EndpointName = &credentials.Endpoint.Name q := tx.Create(&newRepo) if q.Error != nil { return errors.Wrap(q.Error, "creating repository") } - - newRepo.Credentials = creds - newRepo.Endpoint = creds.Endpoint - return nil }) if err != nil { return params.Repository{}, errors.Wrap(err, "creating repository") } - param, err = s.sqlToCommonRepository(newRepo, true) + repo, err := s.getRepoByID(ctx, s.conn, newRepo.ID.String(), "Endpoint", "Credentials", "GiteaCredentials", "Credentials.Endpoint", "GiteaCredentials.Endpoint") + if err != nil { + return params.Repository{}, errors.Wrap(err, "creating repository") + } + + param, err = s.sqlToCommonRepository(repo, true) if err != nil { return params.Repository{}, errors.Wrap(err, "creating repository") } @@ -102,7 +102,9 @@ func (s *sqlDatabase) ListRepositories(_ context.Context) ([]params.Repository, var repos []Repository q := s.conn. Preload("Credentials"). + Preload("GiteaCredentials"). Preload("Credentials.Endpoint"). + Preload("GiteaCredentials.Endpoint"). Preload("Endpoint"). Find(&repos) if q.Error != nil { @@ -122,7 +124,7 @@ func (s *sqlDatabase) ListRepositories(_ context.Context) ([]params.Repository, } func (s *sqlDatabase) DeleteRepository(ctx context.Context, repoID string) (err error) { - repo, err := s.getRepoByID(ctx, s.conn, repoID, "Endpoint", "Credentials", "Credentials.Endpoint") + repo, err := s.getRepoByID(ctx, s.conn, repoID, "Endpoint", "Credentials", "Credentials.Endpoint", "GiteaCredentials", "GiteaCredentials.Endpoint") if err != nil { return errors.Wrap(err, "fetching repo") } @@ -165,7 +167,6 @@ func (s *sqlDatabase) UpdateRepository(ctx context.Context, repoID string, param } if param.CredentialsName != "" { - repo.CredentialsName = param.CredentialsName creds, err = s.getGithubCredentialsByName(ctx, tx, param.CredentialsName, false) if err != nil { return errors.Wrap(err, "fetching credentials") @@ -203,7 +204,7 @@ func (s *sqlDatabase) UpdateRepository(ctx context.Context, repoID string, param return params.Repository{}, errors.Wrap(err, "saving repo") } - repo, err = s.getRepoByID(ctx, s.conn, repoID, "Endpoint", "Credentials", "Credentials.Endpoint") + repo, err = s.getRepoByID(ctx, s.conn, repoID, "Endpoint", "Credentials", "Credentials.Endpoint", "GiteaCredentials", "GiteaCredentials.Endpoint") if err != nil { return params.Repository{}, errors.Wrap(err, "updating enterprise") } @@ -216,7 +217,7 @@ func (s *sqlDatabase) UpdateRepository(ctx context.Context, repoID string, param } func (s *sqlDatabase) GetRepositoryByID(ctx context.Context, repoID string) (params.Repository, error) { - repo, err := s.getRepoByID(ctx, s.conn, repoID, "Pools", "Credentials", "Endpoint", "Credentials.Endpoint") + repo, err := s.getRepoByID(ctx, s.conn, repoID, "Pools", "Credentials", "Endpoint", "Credentials.Endpoint", "GiteaCredentials", "GiteaCredentials.Endpoint") if err != nil { return params.Repository{}, errors.Wrap(err, "fetching repo") } @@ -234,6 +235,8 @@ func (s *sqlDatabase) getRepo(_ context.Context, owner, name, endpointName strin q := s.conn.Where("name = ? COLLATE NOCASE and owner = ? COLLATE NOCASE and endpoint_name = ? COLLATE NOCASE", name, owner, endpointName). Preload("Credentials"). Preload("Credentials.Endpoint"). + Preload("GiteaCredentials"). + Preload("GiteaCredentials.Endpoint"). Preload("Endpoint"). First(&repo) diff --git a/database/sql/repositories_test.go b/database/sql/repositories_test.go index f43b9357..73104a2f 100644 --- a/database/sql/repositories_test.go +++ b/database/sql/repositories_test.go @@ -58,8 +58,8 @@ type RepoTestSuite struct { adminCtx context.Context adminUserID string - testCreds params.GithubCredentials - secondaryTestCreds params.GithubCredentials + testCreds params.ForgeCredentials + secondaryTestCreds params.ForgeCredentials githubEndpoint params.ForgeEndpoint } @@ -119,7 +119,7 @@ func (s *RepoTestSuite) SetupTest() { adminCtx, fmt.Sprintf("test-owner-%d", i), fmt.Sprintf("test-repo-%d", i), - s.testCreds.Name, + s.testCreds, fmt.Sprintf("test-webhook-secret-%d", i), params.PoolBalancerTypeRoundRobin, ) @@ -204,7 +204,7 @@ func (s *RepoTestSuite) TestCreateRepository() { s.adminCtx, s.Fixtures.CreateRepoParams.Owner, s.Fixtures.CreateRepoParams.Name, - s.Fixtures.CreateRepoParams.CredentialsName, + s.testCreds, s.Fixtures.CreateRepoParams.WebhookSecret, params.PoolBalancerTypeRoundRobin, ) @@ -238,7 +238,7 @@ func (s *RepoTestSuite) TestCreateRepositoryInvalidDBPassphrase() { s.adminCtx, s.Fixtures.CreateRepoParams.Owner, s.Fixtures.CreateRepoParams.Name, - s.Fixtures.CreateRepoParams.CredentialsName, + s.testCreds, s.Fixtures.CreateRepoParams.WebhookSecret, params.PoolBalancerTypeRoundRobin, ) @@ -267,7 +267,7 @@ func (s *RepoTestSuite) TestCreateRepositoryInvalidDBCreateErr() { s.adminCtx, s.Fixtures.CreateRepoParams.Owner, s.Fixtures.CreateRepoParams.Name, - s.Fixtures.CreateRepoParams.CredentialsName, + s.testCreds, s.Fixtures.CreateRepoParams.WebhookSecret, params.PoolBalancerTypeRoundRobin, ) diff --git a/database/sql/scalesets_test.go b/database/sql/scalesets_test.go index 9b8b241d..1313af59 100644 --- a/database/sql/scalesets_test.go +++ b/database/sql/scalesets_test.go @@ -19,7 +19,7 @@ type ScaleSetsTestSuite struct { suite.Suite Store dbCommon.Store adminCtx context.Context - creds params.GithubCredentials + creds params.ForgeCredentials org params.Organization repo params.Repository @@ -53,7 +53,7 @@ func (s *ScaleSetsTestSuite) SetupTest() { s.FailNow(fmt.Sprintf("failed to create org: %s", err)) } - s.repo, err = s.Store.CreateRepository(s.adminCtx, "test-org", "test-repo", s.creds.Name, "test-webhookSecret", params.PoolBalancerTypeRoundRobin) + s.repo, err = s.Store.CreateRepository(s.adminCtx, "test-org", "test-repo", s.creds, "test-webhookSecret", params.PoolBalancerTypeRoundRobin) if err != nil { s.FailNow(fmt.Sprintf("failed to create repo: %s", err)) } diff --git a/database/sql/sql.go b/database/sql/sql.go index 82601316..167e90ed 100644 --- a/database/sql/sql.go +++ b/database/sql/sql.go @@ -435,6 +435,7 @@ func (s *sqlDatabase) migrateDB() error { &User{}, &GithubEndpoint{}, &GithubCredentials{}, + &GiteaCredentials{}, &Tag{}, &Pool{}, &Repository{}, diff --git a/database/sql/util.go b/database/sql/util.go index a2531449..0c71261d 100644 --- a/database/sql/util.go +++ b/database/sql/util.go @@ -27,6 +27,7 @@ import ( runnerErrors "github.com/cloudbase/garm-provider-common/errors" commonParams "github.com/cloudbase/garm-provider-common/params" "github.com/cloudbase/garm-provider-common/util" + "github.com/cloudbase/garm/auth" dbCommon "github.com/cloudbase/garm/database/common" "github.com/cloudbase/garm/params" ) @@ -155,7 +156,7 @@ func (s *sqlDatabase) sqlToCommonOrganization(org Organization, detailed bool) ( } if detailed { - creds, err := s.sqlToCommonGithubCredentials(org.Credentials) + creds, err := s.sqlToCommonForgeCredentials(org.Credentials) if err != nil { return params.Organization{}, errors.Wrap(err, "converting credentials") } @@ -206,7 +207,7 @@ func (s *sqlDatabase) sqlToCommonEnterprise(enterprise Enterprise, detailed bool } if detailed { - creds, err := s.sqlToCommonGithubCredentials(enterprise.Credentials) + creds, err := s.sqlToCommonForgeCredentials(enterprise.Credentials) if err != nil { return params.Enterprise{}, errors.Wrap(err, "converting credentials") } @@ -371,16 +372,28 @@ func (s *sqlDatabase) sqlToCommonRepository(repo Repository, detailed bool) (par Endpoint: endpoint, } + if repo.CredentialsID != nil && repo.GiteaCredentialsID != nil { + return params.Repository{}, runnerErrors.NewConflictError("both gitea and github credentials are set for repo %s", repo.Name) + } + + var forgeCreds params.ForgeCredentials if repo.CredentialsID != nil { ret.CredentialsID = *repo.CredentialsID + forgeCreds, err = s.sqlToCommonForgeCredentials(repo.Credentials) + } + + if repo.GiteaCredentialsID != nil { + ret.CredentialsID = *repo.GiteaCredentialsID + forgeCreds, err = s.sqlGiteaToCommonForgeCredentials(repo.GiteaCredentials) + } + + if err != nil { + return params.Repository{}, errors.Wrap(err, "converting credentials") } if detailed { - creds, err := s.sqlToCommonGithubCredentials(repo.Credentials) - if err != nil { - return params.Repository{}, errors.Wrap(err, "converting credentials") - } - ret.Credentials = creds + ret.Credentials = forgeCreds + ret.CredentialsName = forgeCreds.Name } if ret.PoolBalancerType == "" { @@ -638,7 +651,7 @@ func (s *sqlDatabase) addRepositoryEvent(ctx context.Context, repoID string, eve return errors.Wrap(err, "updating instance") } - msg := InstanceStatusUpdate{ + msg := RepositoryEvent{ Message: statusMessage, EventType: event, EventLevel: eventLevel, @@ -653,8 +666,8 @@ func (s *sqlDatabase) addRepositoryEvent(ctx context.Context, repoID string, eve if err != nil { return errors.Wrap(runnerErrors.ErrBadRequest, "parsing id") } - var latestEvents []OrganizationEvent - q := s.conn.Model(&OrganizationEvent{}). + var latestEvents []RepositoryEvent + q := s.conn.Model(&RepositoryEvent{}). Limit(maxEvents).Order("id desc"). Where("repo_id = ?", repoID).Find(&latestEvents) if q.Error != nil { @@ -662,7 +675,7 @@ func (s *sqlDatabase) addRepositoryEvent(ctx context.Context, repoID string, eve } if len(latestEvents) == maxEvents { lastInList := latestEvents[len(latestEvents)-1] - if err := s.conn.Where("repo_id = ? and id < ?", repoID, lastInList.ID).Unscoped().Delete(&OrganizationEvent{}).Error; err != nil { + if err := s.conn.Where("repo_id = ? and id < ?", repoID, lastInList.ID).Unscoped().Delete(&RepositoryEvent{}).Error; err != nil { return errors.Wrap(err, "deleting old events") } } @@ -676,7 +689,7 @@ func (s *sqlDatabase) addOrgEvent(ctx context.Context, orgID string, event param return errors.Wrap(err, "updating instance") } - msg := InstanceStatusUpdate{ + msg := OrganizationEvent{ Message: statusMessage, EventType: event, EventLevel: eventLevel, @@ -714,7 +727,7 @@ func (s *sqlDatabase) addEnterpriseEvent(ctx context.Context, entID string, even return errors.Wrap(err, "updating instance") } - msg := InstanceStatusUpdate{ + msg := EnterpriseEvent{ Message: statusMessage, EventType: event, EventLevel: eventLevel, @@ -763,3 +776,135 @@ func (s *sqlDatabase) AddEntityEvent(ctx context.Context, entity params.ForgeEnt return errors.Wrap(runnerErrors.ErrBadRequest, "invalid entity type") } } + +func (s *sqlDatabase) sqlToCommonForgeCredentials(creds GithubCredentials) (params.ForgeCredentials, error) { + if len(creds.Payload) == 0 { + return params.ForgeCredentials{}, errors.New("empty credentials payload") + } + data, err := util.Unseal(creds.Payload, []byte(s.cfg.Passphrase)) + if err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "unsealing credentials") + } + + ep, err := s.sqlToCommonGithubEndpoint(creds.Endpoint) + if err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "converting github endpoint") + } + + commonCreds := params.ForgeCredentials{ + ID: creds.ID, + Name: creds.Name, + Description: creds.Description, + APIBaseURL: creds.Endpoint.APIBaseURL, + BaseURL: creds.Endpoint.BaseURL, + UploadBaseURL: creds.Endpoint.UploadBaseURL, + CABundle: creds.Endpoint.CACertBundle, + AuthType: creds.AuthType, + CreatedAt: creds.CreatedAt, + UpdatedAt: creds.UpdatedAt, + ForgeType: creds.Endpoint.EndpointType, + Endpoint: ep, + CredentialsPayload: data, + } + + for _, repo := range creds.Repositories { + commonRepo, err := s.sqlToCommonRepository(repo, false) + if err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "converting github repository") + } + commonCreds.Repositories = append(commonCreds.Repositories, commonRepo) + } + + for _, org := range creds.Organizations { + commonOrg, err := s.sqlToCommonOrganization(org, false) + if err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "converting github organization") + } + commonCreds.Organizations = append(commonCreds.Organizations, commonOrg) + } + + for _, ent := range creds.Enterprises { + commonEnt, err := s.sqlToCommonEnterprise(ent, false) + if err != nil { + return params.ForgeCredentials{}, errors.Wrapf(err, "converting github enterprise: %s", ent.Name) + } + commonCreds.Enterprises = append(commonCreds.Enterprises, commonEnt) + } + + return commonCreds, nil +} + +func (s *sqlDatabase) sqlGiteaToCommonForgeCredentials(creds GiteaCredentials) (params.ForgeCredentials, error) { + if len(creds.Payload) == 0 { + return params.ForgeCredentials{}, errors.New("empty credentials payload") + } + data, err := util.Unseal(creds.Payload, []byte(s.cfg.Passphrase)) + if err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "unsealing credentials") + } + + ep, err := s.sqlToCommonGithubEndpoint(creds.Endpoint) + if err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "converting github endpoint") + } + + commonCreds := params.ForgeCredentials{ + ID: creds.ID, + Name: creds.Name, + Description: creds.Description, + APIBaseURL: creds.Endpoint.APIBaseURL, + BaseURL: creds.Endpoint.BaseURL, + CABundle: creds.Endpoint.CACertBundle, + AuthType: creds.AuthType, + CreatedAt: creds.CreatedAt, + UpdatedAt: creds.UpdatedAt, + ForgeType: creds.Endpoint.EndpointType, + Endpoint: ep, + CredentialsPayload: data, + } + + for _, repo := range creds.Repositories { + commonRepo, err := s.sqlToCommonRepository(repo, false) + if err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "converting github repository") + } + commonCreds.Repositories = append(commonCreds.Repositories, commonRepo) + } + + for _, org := range creds.Organizations { + commonOrg, err := s.sqlToCommonOrganization(org, false) + if err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "converting github organization") + } + commonCreds.Organizations = append(commonCreds.Organizations, commonOrg) + } + + return commonCreds, nil +} + +func (s *sqlDatabase) sqlToCommonGithubEndpoint(ep GithubEndpoint) (params.ForgeEndpoint, error) { + return params.ForgeEndpoint{ + Name: ep.Name, + Description: ep.Description, + APIBaseURL: ep.APIBaseURL, + BaseURL: ep.BaseURL, + UploadBaseURL: ep.UploadBaseURL, + CACertBundle: ep.CACertBundle, + CreatedAt: ep.CreatedAt, + EndpointType: ep.EndpointType, + UpdatedAt: ep.UpdatedAt, + }, nil +} + +func getUIDFromContext(ctx context.Context) (uuid.UUID, error) { + userID := auth.UserID(ctx) + if userID == "" { + return uuid.Nil, errors.Wrap(runnerErrors.ErrUnauthorized, "getting UID from context") + } + + asUUID, err := uuid.Parse(userID) + if err != nil { + return uuid.Nil, errors.Wrap(runnerErrors.ErrUnauthorized, "parsing UID from context") + } + return asUUID, nil +} diff --git a/database/watcher/filters.go b/database/watcher/filters.go index 51820270..c355890b 100644 --- a/database/watcher/filters.go +++ b/database/watcher/filters.go @@ -189,7 +189,7 @@ func WithForgeCredentialsFilter(creds params.ForgeCredentials) dbCommon.PayloadF var ok bool switch payload.EntityType { case dbCommon.GithubCredentialsEntityType: - idGetter, ok = payload.Payload.(params.GithubCredentials) + idGetter, ok = payload.Payload.(params.ForgeCredentials) default: return false } diff --git a/database/watcher/watcher_store_test.go b/database/watcher/watcher_store_test.go index 2300ac0a..8791a514 100644 --- a/database/watcher/watcher_store_test.go +++ b/database/watcher/watcher_store_test.go @@ -155,7 +155,7 @@ func (s *WatcherStoreTestSuite) TestInstanceWatcher() { creds := garmTesting.CreateTestGithubCredentials(s.ctx, "test-creds", s.store, s.T(), ep) s.T().Cleanup(func() { s.store.DeleteGithubCredentials(s.ctx, creds.ID) }) - repo, err := s.store.CreateRepository(s.ctx, "test-owner", "test-repo", creds.Name, "test-secret", params.PoolBalancerTypeRoundRobin) + repo, err := s.store.CreateRepository(s.ctx, "test-owner", "test-repo", creds, "test-secret", params.PoolBalancerTypeRoundRobin) s.Require().NoError(err) s.Require().NotEmpty(repo.ID) s.T().Cleanup(func() { s.store.DeleteRepository(s.ctx, repo.ID) }) @@ -259,7 +259,7 @@ func (s *WatcherStoreTestSuite) TestScaleSetInstanceWatcher() { creds := garmTesting.CreateTestGithubCredentials(s.ctx, "test-creds", s.store, s.T(), ep) s.T().Cleanup(func() { s.store.DeleteGithubCredentials(s.ctx, creds.ID) }) - repo, err := s.store.CreateRepository(s.ctx, "test-owner", "test-repo", creds.Name, "test-secret", params.PoolBalancerTypeRoundRobin) + repo, err := s.store.CreateRepository(s.ctx, "test-owner", "test-repo", creds, "test-secret", params.PoolBalancerTypeRoundRobin) s.Require().NoError(err) s.Require().NotEmpty(repo.ID) s.T().Cleanup(func() { s.store.DeleteRepository(s.ctx, repo.ID) }) @@ -369,7 +369,7 @@ func (s *WatcherStoreTestSuite) TestPoolWatcher() { } }) - repo, err := s.store.CreateRepository(s.ctx, "test-owner", "test-repo", creds.Name, "test-secret", params.PoolBalancerTypeRoundRobin) + repo, err := s.store.CreateRepository(s.ctx, "test-owner", "test-repo", creds, "test-secret", params.PoolBalancerTypeRoundRobin) s.Require().NoError(err) s.Require().NotEmpty(repo.ID) s.T().Cleanup(func() { s.store.DeleteRepository(s.ctx, repo.ID) }) @@ -490,7 +490,7 @@ func (s *WatcherStoreTestSuite) TestScaleSetWatcher() { } }) - repo, err := s.store.CreateRepository(s.ctx, "test-owner", "test-repo", creds.Name, "test-secret", params.PoolBalancerTypeRoundRobin) + repo, err := s.store.CreateRepository(s.ctx, "test-owner", "test-repo", creds, "test-secret", params.PoolBalancerTypeRoundRobin) s.Require().NoError(err) s.Require().NotEmpty(repo.ID) s.T().Cleanup(func() { s.store.DeleteRepository(s.ctx, repo.ID) }) @@ -780,7 +780,7 @@ func (s *WatcherStoreTestSuite) TestRepoWatcher() { creds := garmTesting.CreateTestGithubCredentials(s.ctx, "test-creds", s.store, s.T(), ep) s.T().Cleanup(func() { s.store.DeleteGithubCredentials(s.ctx, creds.ID) }) - repo, err := s.store.CreateRepository(s.ctx, "test-owner", "test-repo", creds.Name, "test-secret", params.PoolBalancerTypeRoundRobin) + repo, err := s.store.CreateRepository(s.ctx, "test-owner", "test-repo", creds, "test-secret", params.PoolBalancerTypeRoundRobin) s.Require().NoError(err) s.Require().NotEmpty(repo.ID) @@ -898,7 +898,7 @@ func (s *WatcherStoreTestSuite) TestGithubCredentialsWatcher() { EntityType: common.GithubCredentialsEntityType, Operation: common.DeleteOperation, // We only get the ID and Name of the deleted entity - Payload: params.GithubCredentials{ID: ghCred.ID, Name: ghCred.Name}, + Payload: params.ForgeCredentials{ID: ghCred.ID, Name: ghCred.Name}, }, event) case <-time.After(1 * time.Second): s.T().Fatal("expected payload not received") diff --git a/go.mod b/go.mod index a0b3901f..5070dbfe 100644 --- a/go.mod +++ b/go.mod @@ -29,6 +29,7 @@ require ( github.com/spf13/cobra v1.9.1 github.com/stretchr/testify v1.10.0 golang.org/x/crypto v0.38.0 + golang.org/x/mod v0.17.0 golang.org/x/oauth2 v0.30.0 golang.org/x/sync v0.14.0 gopkg.in/DATA-DOG/go-sqlmock.v1 v1.3.0 diff --git a/go.sum b/go.sum index 3c9af9bb..1cbc5ee0 100644 --- a/go.sum +++ b/go.sum @@ -190,6 +190,8 @@ go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc= golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8= golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw= +golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= +golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY= golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds= golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI= diff --git a/internal/testing/testing.go b/internal/testing/testing.go index 6f253267..0fcc1dda 100644 --- a/internal/testing/testing.go +++ b/internal/testing/testing.go @@ -110,7 +110,7 @@ func CreateDefaultGithubEndpoint(ctx context.Context, db common.Store, s *testin return ep } -func CreateTestGithubCredentials(ctx context.Context, credsName string, db common.Store, s *testing.T, endpoint params.ForgeEndpoint) params.GithubCredentials { +func CreateTestGithubCredentials(ctx context.Context, credsName string, db common.Store, s *testing.T, endpoint params.ForgeEndpoint) params.ForgeCredentials { newCredsParams := params.CreateGithubCredentialsParams{ Name: credsName, Description: "Test creds", diff --git a/params/params.go b/params/params.go index daa54b61..73afa0f4 100644 --- a/params/params.go +++ b/params/params.go @@ -344,26 +344,30 @@ type Tag struct { type Pool struct { RunnerPrefix - ID string `json:"id,omitempty"` - ProviderName string `json:"provider_name,omitempty"` - MaxRunners uint `json:"max_runners,omitempty"` - MinIdleRunners uint `json:"min_idle_runners,omitempty"` - Image string `json:"image,omitempty"` - Flavor string `json:"flavor,omitempty"` - OSType commonParams.OSType `json:"os_type,omitempty"` - OSArch commonParams.OSArch `json:"os_arch,omitempty"` - Tags []Tag `json:"tags,omitempty"` - Enabled bool `json:"enabled,omitempty"` - Instances []Instance `json:"instances,omitempty"` - RepoID string `json:"repo_id,omitempty"` - RepoName string `json:"repo_name,omitempty"` - OrgID string `json:"org_id,omitempty"` - OrgName string `json:"org_name,omitempty"` - EnterpriseID string `json:"enterprise_id,omitempty"` - EnterpriseName string `json:"enterprise_name,omitempty"` - RunnerBootstrapTimeout uint `json:"runner_bootstrap_timeout,omitempty"` - CreatedAt time.Time `json:"created_at,omitempty"` - UpdatedAt time.Time `json:"updated_at,omitempty"` + ID string `json:"id,omitempty"` + ProviderName string `json:"provider_name,omitempty"` + MaxRunners uint `json:"max_runners,omitempty"` + MinIdleRunners uint `json:"min_idle_runners,omitempty"` + Image string `json:"image,omitempty"` + Flavor string `json:"flavor,omitempty"` + OSType commonParams.OSType `json:"os_type,omitempty"` + OSArch commonParams.OSArch `json:"os_arch,omitempty"` + Tags []Tag `json:"tags,omitempty"` + Enabled bool `json:"enabled,omitempty"` + Instances []Instance `json:"instances,omitempty"` + + RepoID string `json:"repo_id,omitempty"` + RepoName string `json:"repo_name,omitempty"` + + OrgID string `json:"org_id,omitempty"` + OrgName string `json:"org_name,omitempty"` + + EnterpriseID string `json:"enterprise_id,omitempty"` + EnterpriseName string `json:"enterprise_name,omitempty"` + + RunnerBootstrapTimeout uint `json:"runner_bootstrap_timeout,omitempty"` + CreatedAt time.Time `json:"created_at,omitempty"` + UpdatedAt time.Time `json:"updated_at,omitempty"` // ExtraSpecs is an opaque raw json that gets sent to the provider // as part of the bootstrap params for instances. It can contain // any kind of data needed by providers. The contents of this field means @@ -586,9 +590,11 @@ type Repository struct { // CredentialName is the name of the credentials associated with the enterprise. // This field is now deprecated. Use CredentialsID instead. This field will be // removed in v0.2.0. - CredentialsName string `json:"credentials_name,omitempty"` - CredentialsID uint `json:"credentials_id,omitempty"` - Credentials GithubCredentials `json:"credentials,omitempty"` + CredentialsName string `json:"credentials_name,omitempty"` + + CredentialsID uint `json:"credentials_id,omitempty"` + Credentials ForgeCredentials `json:"credentials,omitempty"` + PoolManagerStatus PoolManagerStatus `json:"pool_manager_status,omitempty"` PoolBalancerType PoolBalancerType `json:"pool_balancing_type,omitempty"` Endpoint ForgeEndpoint `json:"endpoint,omitempty"` @@ -598,6 +604,13 @@ type Repository struct { WebhookSecret string `json:"-"` } +func (r Repository) GetCredentialsName() string { + if r.CredentialsName != "" { + return r.CredentialsName + } + return r.Credentials.Name +} + func (r Repository) CreationDateGetter() time.Time { return r.CreatedAt } @@ -612,13 +625,10 @@ func (r Repository) GetEntity() (ForgeEntity, error) { Owner: r.Owner, Name: r.Name, PoolBalancerType: r.PoolBalancerType, - Credentials: ForgeCredentials{ - ForgeType: GithubEndpointType, - GithubCredentials: r.Credentials, - }, - WebhookSecret: r.WebhookSecret, - CreatedAt: r.CreatedAt, - UpdatedAt: r.UpdatedAt, + Credentials: r.Credentials, + WebhookSecret: r.WebhookSecret, + CreatedAt: r.CreatedAt, + UpdatedAt: r.UpdatedAt, }, nil } @@ -652,7 +662,7 @@ type Organization struct { // This field is now deprecated. Use CredentialsID instead. This field will be // removed in v0.2.0. CredentialsName string `json:"credentials_name,omitempty"` - Credentials GithubCredentials `json:"credentials,omitempty"` + Credentials ForgeCredentials `json:"credentials,omitempty"` CredentialsID uint `json:"credentials_id,omitempty"` PoolManagerStatus PoolManagerStatus `json:"pool_manager_status,omitempty"` PoolBalancerType PoolBalancerType `json:"pool_balancing_type,omitempty"` @@ -677,12 +687,9 @@ func (o Organization) GetEntity() (ForgeEntity, error) { Owner: o.Name, WebhookSecret: o.WebhookSecret, PoolBalancerType: o.PoolBalancerType, - Credentials: ForgeCredentials{ - ForgeType: GithubEndpointType, - GithubCredentials: o.Credentials, - }, - CreatedAt: o.CreatedAt, - UpdatedAt: o.UpdatedAt, + Credentials: o.Credentials, + CreatedAt: o.CreatedAt, + UpdatedAt: o.UpdatedAt, }, nil } @@ -712,7 +719,7 @@ type Enterprise struct { // This field is now deprecated. Use CredentialsID instead. This field will be // removed in v0.2.0. CredentialsName string `json:"credentials_name,omitempty"` - Credentials GithubCredentials `json:"credentials,omitempty"` + Credentials ForgeCredentials `json:"credentials,omitempty"` CredentialsID uint `json:"credentials_id,omitempty"` PoolManagerStatus PoolManagerStatus `json:"pool_manager_status,omitempty"` PoolBalancerType PoolBalancerType `json:"pool_balancing_type,omitempty"` @@ -737,12 +744,9 @@ func (e Enterprise) GetEntity() (ForgeEntity, error) { Owner: e.Name, WebhookSecret: e.WebhookSecret, PoolBalancerType: e.PoolBalancerType, - Credentials: ForgeCredentials{ - ForgeType: GithubEndpointType, - GithubCredentials: e.Credentials, - }, - CreatedAt: e.CreatedAt, - UpdatedAt: e.UpdatedAt, + Credentials: e.Credentials, + CreatedAt: e.CreatedAt, + UpdatedAt: e.UpdatedAt, }, nil } @@ -856,99 +860,6 @@ func (g GithubRateLimit) ResetAt() time.Time { } type ForgeCredentials struct { - ForgeType EndpointType `json:"type,omitempty"` - GithubCredentials GithubCredentials `json:"github,omitempty"` -} - -func (f ForgeCredentials) CABundle() []byte { - switch f.ForgeType { - case GithubEndpointType: - return f.GithubCredentials.CABundle - case GiteaEndpointType: - return nil - default: - return nil - } -} - -func (f ForgeCredentials) Endpoint() ForgeEndpoint { - switch f.ForgeType { - case GithubEndpointType: - return f.GithubCredentials.Endpoint - case GiteaEndpointType: - return ForgeEndpoint{} - default: - return ForgeEndpoint{} - } -} - -func (f ForgeCredentials) APIBaseURL() string { - switch f.ForgeType { - case GithubEndpointType: - return f.GithubCredentials.APIBaseURL - case GiteaEndpointType: - return "" - default: - return "" - } -} - -func (f ForgeCredentials) UploadBaseURL() string { - switch f.ForgeType { - case GithubEndpointType: - return f.GithubCredentials.UploadBaseURL - case GiteaEndpointType: - return "" - default: - return "" - } -} - -func (f ForgeCredentials) BaseURL() string { - switch f.ForgeType { - case GithubEndpointType: - return f.GithubCredentials.BaseURL - case GiteaEndpointType: - return "" - default: - return "" - } -} - -func (f ForgeCredentials) GetHTTPClient(ctx context.Context) (*http.Client, error) { - switch f.ForgeType { - case GithubEndpointType: - return f.GithubCredentials.GetHTTPClient(ctx) - case GiteaEndpointType: - return nil, fmt.Errorf("gitea credentials not supported") - default: - return nil, fmt.Errorf("unknown credentials type") - } -} - -func (f ForgeCredentials) GetID() uint { - switch f.ForgeType { - case GithubEndpointType: - return f.GithubCredentials.ID - case GiteaEndpointType: - return 0 - default: - return 0 - } -} - -func (f ForgeCredentials) RootCertificateBundle() (CertificateBundle, error) { - switch f.ForgeType { - case GithubEndpointType: - return f.GithubCredentials.RootCertificateBundle() - case GiteaEndpointType: - return CertificateBundle{}, fmt.Errorf("gitea credentials not supported") - default: - return CertificateBundle{}, fmt.Errorf("unknown credentials type") - } -} - -type GithubCredentials struct { ID uint `json:"id,omitempty"` Name string `json:"name,omitempty"` Description string `json:"description,omitempty"` @@ -958,30 +869,25 @@ type GithubCredentials struct { CABundle []byte `json:"ca_bundle,omitempty"` AuthType ForgeAuthType `json:"auth-type,omitempty"` - Repositories []Repository `json:"repositories,omitempty"` - Organizations []Organization `json:"organizations,omitempty"` - Enterprises []Enterprise `json:"enterprises,omitempty"` - Endpoint ForgeEndpoint `json:"endpoint,omitempty"` - CreatedAt time.Time `json:"created_at,omitempty"` - UpdatedAt time.Time `json:"updated_at,omitempty"` - RateLimit GithubRateLimit `json:"rate_limit,omitempty"` + ForgeType EndpointType `json:"forge_type,omitempty"` + + Repositories []Repository `json:"repositories,omitempty"` + Organizations []Organization `json:"organizations,omitempty"` + Enterprises []Enterprise `json:"enterprises,omitempty"` + Endpoint ForgeEndpoint `json:"endpoint,omitempty"` + CreatedAt time.Time `json:"created_at,omitempty"` + UpdatedAt time.Time `json:"updated_at,omitempty"` + RateLimit *GithubRateLimit `json:"rate_limit,omitempty"` // Do not serialize sensitive info. CredentialsPayload []byte `json:"-"` } -func (g GithubCredentials) GetID() uint { +func (g ForgeCredentials) GetID() uint { return g.ID } -func (g GithubCredentials) GetForgeCredentials() ForgeCredentials { - return ForgeCredentials{ - ForgeType: GithubEndpointType, - GithubCredentials: g, - } -} - -func (g GithubCredentials) GetHTTPClient(ctx context.Context) (*http.Client, error) { +func (g ForgeCredentials) GetHTTPClient(ctx context.Context) (*http.Client, error) { var roots *x509.CertPool if g.CABundle != nil { roots = x509.NewCertPool() @@ -1036,7 +942,7 @@ func (g GithubCredentials) GetHTTPClient(ctx context.Context) (*http.Client, err return tc, nil } -func (g GithubCredentials) RootCertificateBundle() (CertificateBundle, error) { +func (g ForgeCredentials) RootCertificateBundle() (CertificateBundle, error) { if len(g.CABundle) == 0 { return CertificateBundle{}, nil } @@ -1067,7 +973,7 @@ func (g GithubCredentials) RootCertificateBundle() (CertificateBundle, error) { } // used by swagger client generated code -type Credentials []GithubCredentials +type Credentials []ForgeCredentials type Provider struct { Name string `json:"name,omitempty"` @@ -1195,11 +1101,11 @@ func (g ForgeEntity) GetCreatedAt() time.Time { func (g ForgeEntity) ForgeURL() string { switch g.EntityType { case ForgeEntityTypeRepository: - return fmt.Sprintf("%s/%s/%s", g.Credentials.BaseURL(), g.Owner, g.Name) + return fmt.Sprintf("%s/%s/%s", g.Credentials.BaseURL, g.Owner, g.Name) case ForgeEntityTypeOrganization: - return fmt.Sprintf("%s/%s", g.Credentials.BaseURL(), g.Owner) + return fmt.Sprintf("%s/%s", g.Credentials.BaseURL, g.Owner) case ForgeEntityTypeEnterprise: - return fmt.Sprintf("%s/enterprises/%s", g.Credentials.BaseURL(), g.Owner) + return fmt.Sprintf("%s/enterprises/%s", g.Credentials.BaseURL, g.Owner) } return "" } diff --git a/params/requests.go b/params/requests.go index 7ab1fa91..82cbf113 100644 --- a/params/requests.go +++ b/params/requests.go @@ -45,6 +45,16 @@ type CreateRepoParams struct { CredentialsName string `json:"credentials_name,omitempty"` WebhookSecret string `json:"webhook_secret,omitempty"` PoolBalancerType PoolBalancerType `json:"pool_balancer_type,omitempty"` + ForgeType EndpointType `json:"forge_type,omitempty"` +} + +func (c CreateRepoParams) GetForgeType() EndpointType { + switch c.ForgeType { + case GithubEndpointType, GiteaEndpointType: + return c.ForgeType + default: + return GithubEndpointType + } } func (c *CreateRepoParams) Validate() error { @@ -77,6 +87,16 @@ type CreateOrgParams struct { CredentialsName string `json:"credentials_name,omitempty"` WebhookSecret string `json:"webhook_secret,omitempty"` PoolBalancerType PoolBalancerType `json:"pool_balancer_type,omitempty"` + ForgeType EndpointType `json:"forge_type,omitempty"` +} + +func (c CreateOrgParams) GetForgeType() EndpointType { + switch c.ForgeType { + case GithubEndpointType, GiteaEndpointType: + return c.ForgeType + default: + return GithubEndpointType + } } func (c *CreateOrgParams) Validate() error { @@ -281,7 +301,6 @@ type CreateGithubEndpointParams struct { APIBaseURL string `json:"api_base_url,omitempty"` UploadBaseURL string `json:"upload_base_url,omitempty"` BaseURL string `json:"base_url,omitempty"` - EndpointType string `json:"endpoint_type,omitempty"` CACertBundle []byte `json:"ca_cert_bundle,omitempty"` } @@ -290,14 +309,6 @@ func (c CreateGithubEndpointParams) Validate() error { return runnerErrors.NewBadRequestError("missing api_base_url") } - if c.EndpointType != "" { - switch c.EndpointType { - case string(GithubEndpointType), string(GiteaEndpointType): - default: - return runnerErrors.NewBadRequestError("invalid endpoint_type: %s", c.EndpointType) - } - } - url, err := url.Parse(c.APIBaseURL) if err != nil || url.Scheme == "" || url.Host == "" { return runnerErrors.NewBadRequestError("invalid api_base_url") @@ -308,21 +319,19 @@ func (c CreateGithubEndpointParams) Validate() error { return runnerErrors.NewBadRequestError("invalid api_base_url") } - if c.EndpointType == string(GithubEndpointType) { - if c.UploadBaseURL == "" { - return runnerErrors.NewBadRequestError("missing upload_base_url") - } + if c.UploadBaseURL == "" { + return runnerErrors.NewBadRequestError("missing upload_base_url") + } - url, err = url.Parse(c.UploadBaseURL) - if err != nil || url.Scheme == "" || url.Host == "" { - return runnerErrors.NewBadRequestError("invalid upload_base_url") - } + url, err = url.Parse(c.UploadBaseURL) + if err != nil || url.Scheme == "" || url.Host == "" { + return runnerErrors.NewBadRequestError("invalid upload_base_url") + } - switch url.Scheme { - case httpsScheme, httpScheme: - default: - return runnerErrors.NewBadRequestError("invalid api_base_url") - } + switch url.Scheme { + case httpsScheme, httpScheme: + default: + return runnerErrors.NewBadRequestError("invalid api_base_url") } if c.BaseURL == "" { @@ -617,3 +626,154 @@ type UpdateScaleSetParams struct { State *ScaleSetState `json:"state"` ExtendedState *string `json:"extended_state"` } + +type CreateGiteaEndpointParams struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + APIBaseURL string `json:"api_base_url,omitempty"` + BaseURL string `json:"base_url,omitempty"` + CACertBundle []byte `json:"ca_cert_bundle,omitempty"` +} + +func (c CreateGiteaEndpointParams) Validate() error { + if c.APIBaseURL == "" { + return runnerErrors.NewBadRequestError("missing api_base_url") + } + + url, err := url.Parse(c.APIBaseURL) + if err != nil || url.Scheme == "" || url.Host == "" { + return runnerErrors.NewBadRequestError("invalid api_base_url") + } + switch url.Scheme { + case httpsScheme, httpScheme: + default: + return runnerErrors.NewBadRequestError("invalid api_base_url") + } + + switch url.Scheme { + case httpsScheme, httpScheme: + default: + return runnerErrors.NewBadRequestError("invalid api_base_url") + } + + if c.BaseURL == "" { + return runnerErrors.NewBadRequestError("missing base_url") + } + + url, err = url.Parse(c.BaseURL) + if err != nil || url.Scheme == "" || url.Host == "" { + return runnerErrors.NewBadRequestError("invalid base_url") + } + + switch url.Scheme { + case httpsScheme, httpScheme: + default: + return runnerErrors.NewBadRequestError("invalid api_base_url") + } + + if c.CACertBundle != nil { + block, _ := pem.Decode(c.CACertBundle) + if block == nil { + return runnerErrors.NewBadRequestError("invalid ca_cert_bundle") + } + if _, err := x509.ParseCertificates(block.Bytes); err != nil { + return runnerErrors.NewBadRequestError("invalid ca_cert_bundle") + } + } + + return nil +} + +type UpdateGiteaEndpointParams struct { + Description *string `json:"description,omitempty"` + APIBaseURL *string `json:"api_base_url,omitempty"` + BaseURL *string `json:"base_url,omitempty"` + CACertBundle []byte `json:"ca_cert_bundle,omitempty"` +} + +func (u UpdateGiteaEndpointParams) Validate() error { + if u.APIBaseURL != nil { + url, err := url.Parse(*u.APIBaseURL) + if err != nil || url.Scheme == "" || url.Host == "" { + return runnerErrors.NewBadRequestError("invalid api_base_url") + } + switch url.Scheme { + case httpsScheme, httpScheme: + default: + return runnerErrors.NewBadRequestError("invalid api_base_url") + } + } + + if u.BaseURL != nil { + url, err := url.Parse(*u.BaseURL) + if err != nil || url.Scheme == "" || url.Host == "" { + return runnerErrors.NewBadRequestError("invalid base_url") + } + switch url.Scheme { + case httpsScheme, httpScheme: + default: + return runnerErrors.NewBadRequestError("invalid api_base_url") + } + } + + if u.CACertBundle != nil { + block, _ := pem.Decode(u.CACertBundle) + if block == nil { + return runnerErrors.NewBadRequestError("invalid ca_cert_bundle") + } + if _, err := x509.ParseCertificates(block.Bytes); err != nil { + return runnerErrors.NewBadRequestError("invalid ca_cert_bundle") + } + } + + return nil +} + +type CreateGiteaCredentialsParams struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + Endpoint string `json:"endpoint,omitempty"` + AuthType ForgeAuthType `json:"auth_type,omitempty"` + PAT GithubPAT `json:"pat,omitempty"` + App GithubApp `json:"app,omitempty"` +} + +func (c CreateGiteaCredentialsParams) Validate() error { + if c.Name == "" { + return runnerErrors.NewBadRequestError("missing name") + } + + if c.Endpoint == "" { + return runnerErrors.NewBadRequestError("missing endpoint") + } + + switch c.AuthType { + case ForgeAuthTypePAT: + default: + return runnerErrors.NewBadRequestError("invalid auth_type: %s", c.AuthType) + } + + if c.AuthType == ForgeAuthTypePAT { + if c.PAT.OAuth2Token == "" { + return runnerErrors.NewBadRequestError("missing oauth2_token") + } + } + + return nil +} + +type UpdateGiteaCredentialsParams struct { + Name *string `json:"name,omitempty"` + Description *string `json:"description,omitempty"` + PAT *GithubPAT `json:"pat,omitempty"` +} + +func (u UpdateGiteaCredentialsParams) Validate() error { + if u.PAT != nil { + if u.PAT.OAuth2Token == "" { + return runnerErrors.NewBadRequestError("missing oauth2_token") + } + } + + return nil +} diff --git a/runner/common/mocks/GithubClient.go b/runner/common/mocks/GithubClient.go index 6ba39d48..36ef1079 100644 --- a/runner/common/mocks/GithubClient.go +++ b/runner/common/mocks/GithubClient.go @@ -342,7 +342,7 @@ func (_m *GithubClient) ListEntityRunnerApplicationDownloads(ctx context.Context } // ListEntityRunners provides a mock function with given fields: ctx, opts -func (_m *GithubClient) ListEntityRunners(ctx context.Context, opts *github.ListOptions) (*github.Runners, *github.Response, error) { +func (_m *GithubClient) ListEntityRunners(ctx context.Context, opts *github.ListRunnersOptions) (*github.Runners, *github.Response, error) { ret := _m.Called(ctx, opts) if len(ret) == 0 { @@ -352,10 +352,10 @@ func (_m *GithubClient) ListEntityRunners(ctx context.Context, opts *github.List var r0 *github.Runners var r1 *github.Response var r2 error - if rf, ok := ret.Get(0).(func(context.Context, *github.ListOptions) (*github.Runners, *github.Response, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, *github.ListRunnersOptions) (*github.Runners, *github.Response, error)); ok { return rf(ctx, opts) } - if rf, ok := ret.Get(0).(func(context.Context, *github.ListOptions) *github.Runners); ok { + if rf, ok := ret.Get(0).(func(context.Context, *github.ListRunnersOptions) *github.Runners); ok { r0 = rf(ctx, opts) } else { if ret.Get(0) != nil { @@ -363,7 +363,7 @@ func (_m *GithubClient) ListEntityRunners(ctx context.Context, opts *github.List } } - if rf, ok := ret.Get(1).(func(context.Context, *github.ListOptions) *github.Response); ok { + if rf, ok := ret.Get(1).(func(context.Context, *github.ListRunnersOptions) *github.Response); ok { r1 = rf(ctx, opts) } else { if ret.Get(1) != nil { @@ -371,7 +371,7 @@ func (_m *GithubClient) ListEntityRunners(ctx context.Context, opts *github.List } } - if rf, ok := ret.Get(2).(func(context.Context, *github.ListOptions) error); ok { + if rf, ok := ret.Get(2).(func(context.Context, *github.ListRunnersOptions) error); ok { r2 = rf(ctx, opts) } else { r2 = ret.Error(2) @@ -410,6 +410,36 @@ func (_m *GithubClient) PingEntityHook(ctx context.Context, id int64) (*github.R return r0, r1 } +// RateLimit provides a mock function with given fields: ctx +func (_m *GithubClient) RateLimit(ctx context.Context) (*github.RateLimits, error) { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for RateLimit") + } + + var r0 *github.RateLimits + var r1 error + if rf, ok := ret.Get(0).(func(context.Context) (*github.RateLimits, error)); ok { + return rf(ctx) + } + if rf, ok := ret.Get(0).(func(context.Context) *github.RateLimits); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*github.RateLimits) + } + } + + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // RemoveEntityRunner provides a mock function with given fields: ctx, runnerID func (_m *GithubClient) RemoveEntityRunner(ctx context.Context, runnerID int64) error { ret := _m.Called(ctx, runnerID) diff --git a/runner/common/mocks/GithubEntityOperations.go b/runner/common/mocks/GithubEntityOperations.go index 567d4ebc..0aab9943 100644 --- a/runner/common/mocks/GithubEntityOperations.go +++ b/runner/common/mocks/GithubEntityOperations.go @@ -303,7 +303,7 @@ func (_m *GithubEntityOperations) ListEntityRunnerApplicationDownloads(ctx conte } // ListEntityRunners provides a mock function with given fields: ctx, opts -func (_m *GithubEntityOperations) ListEntityRunners(ctx context.Context, opts *github.ListOptions) (*github.Runners, *github.Response, error) { +func (_m *GithubEntityOperations) ListEntityRunners(ctx context.Context, opts *github.ListRunnersOptions) (*github.Runners, *github.Response, error) { ret := _m.Called(ctx, opts) if len(ret) == 0 { @@ -313,10 +313,10 @@ func (_m *GithubEntityOperations) ListEntityRunners(ctx context.Context, opts *g var r0 *github.Runners var r1 *github.Response var r2 error - if rf, ok := ret.Get(0).(func(context.Context, *github.ListOptions) (*github.Runners, *github.Response, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, *github.ListRunnersOptions) (*github.Runners, *github.Response, error)); ok { return rf(ctx, opts) } - if rf, ok := ret.Get(0).(func(context.Context, *github.ListOptions) *github.Runners); ok { + if rf, ok := ret.Get(0).(func(context.Context, *github.ListRunnersOptions) *github.Runners); ok { r0 = rf(ctx, opts) } else { if ret.Get(0) != nil { @@ -324,7 +324,7 @@ func (_m *GithubEntityOperations) ListEntityRunners(ctx context.Context, opts *g } } - if rf, ok := ret.Get(1).(func(context.Context, *github.ListOptions) *github.Response); ok { + if rf, ok := ret.Get(1).(func(context.Context, *github.ListRunnersOptions) *github.Response); ok { r1 = rf(ctx, opts) } else { if ret.Get(1) != nil { @@ -332,7 +332,7 @@ func (_m *GithubEntityOperations) ListEntityRunners(ctx context.Context, opts *g } } - if rf, ok := ret.Get(2).(func(context.Context, *github.ListOptions) error); ok { + if rf, ok := ret.Get(2).(func(context.Context, *github.ListRunnersOptions) error); ok { r2 = rf(ctx, opts) } else { r2 = ret.Error(2) @@ -371,6 +371,36 @@ func (_m *GithubEntityOperations) PingEntityHook(ctx context.Context, id int64) return r0, r1 } +// RateLimit provides a mock function with given fields: ctx +func (_m *GithubEntityOperations) RateLimit(ctx context.Context) (*github.RateLimits, error) { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for RateLimit") + } + + var r0 *github.RateLimits + var r1 error + if rf, ok := ret.Get(0).(func(context.Context) (*github.RateLimits, error)); ok { + return rf(ctx) + } + if rf, ok := ret.Get(0).(func(context.Context) *github.RateLimits); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*github.RateLimits) + } + } + + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // RemoveEntityRunner provides a mock function with given fields: ctx, runnerID func (_m *GithubEntityOperations) RemoveEntityRunner(ctx context.Context, runnerID int64) error { ret := _m.Called(ctx, runnerID) diff --git a/runner/common/mocks/RateLimitClient.go b/runner/common/mocks/RateLimitClient.go new file mode 100644 index 00000000..2c360217 --- /dev/null +++ b/runner/common/mocks/RateLimitClient.go @@ -0,0 +1,59 @@ +// Code generated by mockery v2.53.3. DO NOT EDIT. + +package mocks + +import ( + context "context" + + github "github.com/google/go-github/v71/github" + mock "github.com/stretchr/testify/mock" +) + +// RateLimitClient is an autogenerated mock type for the RateLimitClient type +type RateLimitClient struct { + mock.Mock +} + +// RateLimit provides a mock function with given fields: ctx +func (_m *RateLimitClient) RateLimit(ctx context.Context) (*github.RateLimits, error) { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for RateLimit") + } + + var r0 *github.RateLimits + var r1 error + if rf, ok := ret.Get(0).(func(context.Context) (*github.RateLimits, error)); ok { + return rf(ctx) + } + if rf, ok := ret.Get(0).(func(context.Context) *github.RateLimits); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*github.RateLimits) + } + } + + if rf, ok := ret.Get(1).(func(context.Context) error); ok { + r1 = rf(ctx) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// NewRateLimitClient creates a new instance of RateLimitClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRateLimitClient(t interface { + mock.TestingT + Cleanup(func()) +}) *RateLimitClient { + mock := &RateLimitClient{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/runner/enterprises_test.go b/runner/enterprises_test.go index 7e4545d4..5c09ae5d 100644 --- a/runner/enterprises_test.go +++ b/runner/enterprises_test.go @@ -39,7 +39,7 @@ type EnterpriseTestFixtures struct { Store dbCommon.Store StoreEnterprises map[string]params.Enterprise Providers map[string]common.Provider - Credentials map[string]params.GithubCredentials + Credentials map[string]params.ForgeCredentials CreateEnterpriseParams params.CreateEnterpriseParams CreatePoolParams params.CreatePoolParams CreateInstanceParams params.CreateInstanceParams @@ -56,8 +56,8 @@ type EnterpriseTestSuite struct { Fixtures *EnterpriseTestFixtures Runner *Runner - testCreds params.GithubCredentials - secondaryTestCreds params.GithubCredentials + testCreds params.ForgeCredentials + secondaryTestCreds params.ForgeCredentials forgeEndpoint params.ForgeEndpoint } @@ -103,7 +103,7 @@ func (s *EnterpriseTestSuite) SetupTest() { Providers: map[string]common.Provider{ "test-provider": providerMock, }, - Credentials: map[string]params.GithubCredentials{ + Credentials: map[string]params.ForgeCredentials{ s.testCreds.Name: s.testCreds, s.secondaryTestCreds.Name: s.secondaryTestCreds, }, diff --git a/runner/gitea_credentials.go b/runner/gitea_credentials.go new file mode 100644 index 00000000..749f2346 --- /dev/null +++ b/runner/gitea_credentials.go @@ -0,0 +1,86 @@ +package runner + +import ( + "context" + + "github.com/pkg/errors" + + runnerErrors "github.com/cloudbase/garm-provider-common/errors" + "github.com/cloudbase/garm/auth" + "github.com/cloudbase/garm/params" +) + +func (r *Runner) ListGiteaCredentials(ctx context.Context) ([]params.ForgeCredentials, error) { + if !auth.IsAdmin(ctx) { + return nil, runnerErrors.ErrUnauthorized + } + + // Get the credentials from the store. The cache is always updated after the database successfully + // commits the transaction that created/updated the credentials. + // If we create a set of credentials then immediately after we call ListGiteaCredentials, + // there is a posibillity that not all creds will be in the cache. + creds, err := r.store.ListGiteaCredentials(ctx) + if err != nil { + return nil, errors.Wrap(err, "fetching gitea credentials") + } + return creds, nil +} + +func (r *Runner) CreateGiteaCredentials(ctx context.Context, param params.CreateGiteaCredentialsParams) (params.ForgeCredentials, error) { + if !auth.IsAdmin(ctx) { + return params.ForgeCredentials{}, runnerErrors.ErrUnauthorized + } + + if err := param.Validate(); err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "failed to validate gitea credentials params") + } + + creds, err := r.store.CreateGiteaCredentials(ctx, param) + if err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "failed to create gitea credentials") + } + + return creds, nil +} + +func (r *Runner) GetGiteaCredentials(ctx context.Context, id uint) (params.ForgeCredentials, error) { + if !auth.IsAdmin(ctx) { + return params.ForgeCredentials{}, runnerErrors.ErrUnauthorized + } + + creds, err := r.store.GetGiteaCredentials(ctx, id, true) + if err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "failed to get gitea credentials") + } + + return creds, nil +} + +func (r *Runner) DeleteGiteaCredentials(ctx context.Context, id uint) error { + if !auth.IsAdmin(ctx) { + return runnerErrors.ErrUnauthorized + } + + if err := r.store.DeleteGiteaCredentials(ctx, id); err != nil { + return errors.Wrap(err, "failed to delete gitea credentials") + } + + return nil +} + +func (r *Runner) UpdateGiteaCredentials(ctx context.Context, id uint, param params.UpdateGiteaCredentialsParams) (params.ForgeCredentials, error) { + if !auth.IsAdmin(ctx) { + return params.ForgeCredentials{}, runnerErrors.ErrUnauthorized + } + + if err := param.Validate(); err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "failed to validate gitea credentials params") + } + + newCreds, err := r.store.UpdateGiteaCredentials(ctx, id, param) + if err != nil { + return params.ForgeCredentials{}, errors.Wrap(err, "failed to update gitea credentials") + } + + return newCreds, nil +} diff --git a/runner/gitea_endpoints.go b/runner/gitea_endpoints.go new file mode 100644 index 00000000..847dbab9 --- /dev/null +++ b/runner/gitea_endpoints.go @@ -0,0 +1,82 @@ +package runner + +import ( + "context" + + "github.com/pkg/errors" + + runnerErrors "github.com/cloudbase/garm-provider-common/errors" + "github.com/cloudbase/garm/auth" + "github.com/cloudbase/garm/params" +) + +func (r *Runner) CreateGiteaEndpoint(ctx context.Context, param params.CreateGiteaEndpointParams) (params.ForgeEndpoint, error) { + if !auth.IsAdmin(ctx) { + return params.ForgeEndpoint{}, runnerErrors.ErrUnauthorized + } + + if err := param.Validate(); err != nil { + return params.ForgeEndpoint{}, errors.Wrap(err, "failed to validate gitea endpoint params") + } + + ep, err := r.store.CreateGiteaEndpoint(ctx, param) + if err != nil { + return params.ForgeEndpoint{}, errors.Wrap(err, "failed to create gitea endpoint") + } + + return ep, nil +} + +func (r *Runner) GetGiteaEndpoint(ctx context.Context, name string) (params.ForgeEndpoint, error) { + if !auth.IsAdmin(ctx) { + return params.ForgeEndpoint{}, runnerErrors.ErrUnauthorized + } + endpoint, err := r.store.GetGiteaEndpoint(ctx, name) + if err != nil { + return params.ForgeEndpoint{}, errors.Wrap(err, "failed to get gitea endpoint") + } + + return endpoint, nil +} + +func (r *Runner) DeleteGiteaEndpoint(ctx context.Context, name string) error { + if !auth.IsAdmin(ctx) { + return runnerErrors.ErrUnauthorized + } + + err := r.store.DeleteGiteaEndpoint(ctx, name) + if err != nil { + return errors.Wrap(err, "failed to delete gitea endpoint") + } + + return nil +} + +func (r *Runner) UpdateGiteaEndpoint(ctx context.Context, name string, param params.UpdateGiteaEndpointParams) (params.ForgeEndpoint, error) { + if !auth.IsAdmin(ctx) { + return params.ForgeEndpoint{}, runnerErrors.ErrUnauthorized + } + + if err := param.Validate(); err != nil { + return params.ForgeEndpoint{}, errors.Wrap(err, "failed to validate gitea endpoint params") + } + + newEp, err := r.store.UpdateGiteaEndpoint(ctx, name, param) + if err != nil { + return params.ForgeEndpoint{}, errors.Wrap(err, "failed to update gitea endpoint") + } + return newEp, nil +} + +func (r *Runner) ListGiteaEndpoints(ctx context.Context) ([]params.ForgeEndpoint, error) { + if !auth.IsAdmin(ctx) { + return nil, runnerErrors.ErrUnauthorized + } + + endpoints, err := r.store.ListGiteaEndpoints(ctx) + if err != nil { + return nil, errors.Wrap(err, "failed to list gitea endpoints") + } + + return endpoints, nil +} diff --git a/runner/github_credentials.go b/runner/github_credentials.go index 7cd4e74c..7c368c99 100644 --- a/runner/github_credentials.go +++ b/runner/github_credentials.go @@ -11,7 +11,7 @@ import ( "github.com/cloudbase/garm/params" ) -func (r *Runner) ListCredentials(ctx context.Context) ([]params.GithubCredentials, error) { +func (r *Runner) ListCredentials(ctx context.Context) ([]params.ForgeCredentials, error) { if !auth.IsAdmin(ctx) { return nil, runnerErrors.ErrUnauthorized } @@ -37,31 +37,31 @@ func (r *Runner) ListCredentials(ctx context.Context) ([]params.GithubCredential return creds, nil } -func (r *Runner) CreateGithubCredentials(ctx context.Context, param params.CreateGithubCredentialsParams) (params.GithubCredentials, error) { +func (r *Runner) CreateGithubCredentials(ctx context.Context, param params.CreateGithubCredentialsParams) (params.ForgeCredentials, error) { if !auth.IsAdmin(ctx) { - return params.GithubCredentials{}, runnerErrors.ErrUnauthorized + return params.ForgeCredentials{}, runnerErrors.ErrUnauthorized } if err := param.Validate(); err != nil { - return params.GithubCredentials{}, errors.Wrap(err, "failed to validate github credentials params") + return params.ForgeCredentials{}, errors.Wrap(err, "failed to validate github credentials params") } creds, err := r.store.CreateGithubCredentials(ctx, param) if err != nil { - return params.GithubCredentials{}, errors.Wrap(err, "failed to create github credentials") + return params.ForgeCredentials{}, errors.Wrap(err, "failed to create github credentials") } return creds, nil } -func (r *Runner) GetGithubCredentials(ctx context.Context, id uint) (params.GithubCredentials, error) { +func (r *Runner) GetGithubCredentials(ctx context.Context, id uint) (params.ForgeCredentials, error) { if !auth.IsAdmin(ctx) { - return params.GithubCredentials{}, runnerErrors.ErrUnauthorized + return params.ForgeCredentials{}, runnerErrors.ErrUnauthorized } creds, err := r.store.GetGithubCredentials(ctx, id, true) if err != nil { - return params.GithubCredentials{}, errors.Wrap(err, "failed to get github credentials") + return params.ForgeCredentials{}, errors.Wrap(err, "failed to get github credentials") } cached, ok := cache.GetGithubCredentials((creds.ID)) @@ -84,18 +84,18 @@ func (r *Runner) DeleteGithubCredentials(ctx context.Context, id uint) error { return nil } -func (r *Runner) UpdateGithubCredentials(ctx context.Context, id uint, param params.UpdateGithubCredentialsParams) (params.GithubCredentials, error) { +func (r *Runner) UpdateGithubCredentials(ctx context.Context, id uint, param params.UpdateGithubCredentialsParams) (params.ForgeCredentials, error) { if !auth.IsAdmin(ctx) { - return params.GithubCredentials{}, runnerErrors.ErrUnauthorized + return params.ForgeCredentials{}, runnerErrors.ErrUnauthorized } if err := param.Validate(); err != nil { - return params.GithubCredentials{}, errors.Wrap(err, "failed to validate github credentials params") + return params.ForgeCredentials{}, errors.Wrap(err, "failed to validate github credentials params") } newCreds, err := r.store.UpdateGithubCredentials(ctx, id, param) if err != nil { - return params.GithubCredentials{}, errors.Wrap(err, "failed to update github credentials") + return params.ForgeCredentials{}, errors.Wrap(err, "failed to update github credentials") } return newCreds, nil diff --git a/runner/organizations_test.go b/runner/organizations_test.go index 3609b941..4d4a26e1 100644 --- a/runner/organizations_test.go +++ b/runner/organizations_test.go @@ -39,7 +39,7 @@ type OrgTestFixtures struct { Store dbCommon.Store StoreOrgs map[string]params.Organization Providers map[string]common.Provider - Credentials map[string]params.GithubCredentials + Credentials map[string]params.ForgeCredentials CreateOrgParams params.CreateOrgParams CreatePoolParams params.CreatePoolParams CreateInstanceParams params.CreateInstanceParams @@ -56,8 +56,8 @@ type OrgTestSuite struct { Fixtures *OrgTestFixtures Runner *Runner - testCreds params.GithubCredentials - secondaryTestCreds params.GithubCredentials + testCreds params.ForgeCredentials + secondaryTestCreds params.ForgeCredentials githubEndpoint params.ForgeEndpoint } @@ -104,7 +104,7 @@ func (s *OrgTestSuite) SetupTest() { Providers: map[string]common.Provider{ "test-provider": providerMock, }, - Credentials: map[string]params.GithubCredentials{ + Credentials: map[string]params.ForgeCredentials{ s.testCreds.Name: s.testCreds, s.secondaryTestCreds.Name: s.secondaryTestCreds, }, diff --git a/runner/pool/pool.go b/runner/pool/pool.go index e24aa69b..68de0ec3 100644 --- a/runner/pool/pool.go +++ b/runner/pool/pool.go @@ -83,7 +83,7 @@ func NewEntityPoolManager(ctx context.Context, entity params.ForgeEntity, instan return nil, errors.Wrap(err, "getting controller info") } - consumerID := fmt.Sprintf("pool-manager-%s-%s", entity.String(), entity.Credentials.Endpoint().Name) + consumerID := fmt.Sprintf("pool-manager-%s-%s", entity.String(), entity.Credentials.Endpoint.Name) slog.InfoContext(ctx, "registering consumer", "consumer_id", consumerID) consumer, err := watcher.RegisterConsumer( ctx, consumerID, @@ -887,7 +887,7 @@ func (r *basePoolManager) addInstanceToProvider(instance params.Instance) error Image: pool.Image, ExtraSpecs: pool.ExtraSpecs, PoolID: instance.PoolID, - CACertBundle: r.entity.Credentials.CABundle(), + CACertBundle: r.entity.Credentials.CABundle, GitHubRunnerGroup: instance.GitHubRunnerGroup, JitConfigEnabled: hasJITConfig, } @@ -1366,6 +1366,19 @@ func (r *basePoolManager) deleteInstanceFromProvider(ctx context.Context, instan return nil } +func (r *basePoolManager) sleepWithCancel(sleepTime time.Duration) (canceled bool) { + ticker := time.NewTicker(sleepTime) + defer ticker.Stop() + + select { + case <-ticker.C: + return false + case <-r.quit: + case <-r.ctx.Done(): + } + return true +} + func (r *basePoolManager) deletePendingInstances() error { instances, err := r.store.ListEntityInstances(r.ctx, r.entity) if err != nil { @@ -1414,7 +1427,9 @@ func (r *basePoolManager) deletePendingInstances() error { return fmt.Errorf("failed to generate random number: %w", err) } jitter := time.Duration(num.Int64()) * time.Millisecond - time.Sleep(jitter) + if canceled := r.sleepWithCancel(jitter); canceled { + return nil + } currentStatus := instance.Status deleteMux := false diff --git a/runner/pool/watcher.go b/runner/pool/watcher.go index 56427e89..455f4239 100644 --- a/runner/pool/watcher.go +++ b/runner/pool/watcher.go @@ -125,12 +125,12 @@ func (r *basePoolManager) handleWatcherEvent(event common.ChangePayload) { dbEntityType := common.DatabaseEntityType(r.entity.EntityType) switch event.EntityType { case common.GithubCredentialsEntityType: - credentials, ok := event.Payload.(params.GithubCredentials) + credentials, ok := event.Payload.(params.ForgeCredentials) if !ok { slog.ErrorContext(r.ctx, "failed to cast payload to github credentials") return } - r.handleCredentialsUpdate(credentials.GetForgeCredentials()) + r.handleCredentialsUpdate(credentials) case common.ControllerEntityType: controllerInfo, ok := event.Payload.(params.ControllerInfo) if !ok { diff --git a/runner/pools_test.go b/runner/pools_test.go index 95c6b6bd..587addce 100644 --- a/runner/pools_test.go +++ b/runner/pools_test.go @@ -47,8 +47,8 @@ type PoolTestSuite struct { Runner *Runner adminCtx context.Context - testCreds params.GithubCredentials - secondaryTestCreds params.GithubCredentials + testCreds params.ForgeCredentials + secondaryTestCreds params.ForgeCredentials githubEndpoint params.ForgeEndpoint } diff --git a/runner/repositories.go b/runner/repositories.go index 83876c5d..058e1a02 100644 --- a/runner/repositories.go +++ b/runner/repositories.go @@ -38,7 +38,16 @@ func (r *Runner) CreateRepository(ctx context.Context, param params.CreateRepoPa return params.Repository{}, errors.Wrap(err, "validating params") } - creds, err := r.store.GetGithubCredentialsByName(ctx, param.CredentialsName, true) + var creds params.ForgeCredentials + switch param.GetForgeType() { + case params.GithubEndpointType: + creds, err = r.store.GetGithubCredentialsByName(ctx, param.CredentialsName, true) + case params.GiteaEndpointType: + creds, err = r.store.GetGiteaCredentialsByName(ctx, param.CredentialsName, true) + default: + return params.Repository{}, runnerErrors.NewBadRequestError("invalid forge type: %s", param.GetForgeType()) + } + if err != nil { return params.Repository{}, runnerErrors.NewBadRequestError("credentials %s not defined", param.CredentialsName) } @@ -52,7 +61,7 @@ func (r *Runner) CreateRepository(ctx context.Context, param params.CreateRepoPa return params.Repository{}, runnerErrors.NewConflictError("repository %s/%s already exists", param.Owner, param.Name) } - repo, err = r.store.CreateRepository(ctx, param.Owner, param.Name, creds.Name, param.WebhookSecret, param.PoolBalancerType) + repo, err = r.store.CreateRepository(ctx, param.Owner, param.Name, creds, param.WebhookSecret, param.PoolBalancerType) if err != nil { return params.Repository{}, errors.Wrap(err, "creating repository") } diff --git a/runner/repositories_test.go b/runner/repositories_test.go index 47bfb003..4e891e4b 100644 --- a/runner/repositories_test.go +++ b/runner/repositories_test.go @@ -39,7 +39,7 @@ type RepoTestFixtures struct { Store dbCommon.Store StoreRepos map[string]params.Repository Providers map[string]common.Provider - Credentials map[string]params.GithubCredentials + Credentials map[string]params.ForgeCredentials CreateRepoParams params.CreateRepoParams CreatePoolParams params.CreatePoolParams CreateInstanceParams params.CreateInstanceParams @@ -60,8 +60,8 @@ type RepoTestSuite struct { Fixtures *RepoTestFixtures Runner *Runner - testCreds params.GithubCredentials - secondaryTestCreds params.GithubCredentials + testCreds params.ForgeCredentials + secondaryTestCreds params.ForgeCredentials githubEndpoint params.ForgeEndpoint } @@ -86,7 +86,7 @@ func (s *RepoTestSuite) SetupTest() { adminCtx, fmt.Sprintf("test-owner-%v", i), name, - s.testCreds.Name, + s.testCreds, fmt.Sprintf("test-webhook-secret-%v", i), params.PoolBalancerTypeRoundRobin, ) @@ -107,7 +107,7 @@ func (s *RepoTestSuite) SetupTest() { Providers: map[string]common.Provider{ "test-provider": providerMock, }, - Credentials: map[string]params.GithubCredentials{ + Credentials: map[string]params.ForgeCredentials{ s.testCreds.Name: s.testCreds, s.secondaryTestCreds.Name: s.secondaryTestCreds, }, diff --git a/test/integration/client_utils.go b/test/integration/client_utils.go index 977cc11c..c986be2d 100644 --- a/test/integration/client_utils.go +++ b/test/integration/client_utils.go @@ -51,7 +51,7 @@ func listCredentials(apiCli *client.GarmAPI, apiAuthToken runtime.ClientAuthInfo return listCredentialsResponse.Payload, nil } -func createGithubCredentials(apiCli *client.GarmAPI, apiAuthToken runtime.ClientAuthInfoWriter, credentialsParams params.CreateGithubCredentialsParams) (*params.GithubCredentials, error) { +func createGithubCredentials(apiCli *client.GarmAPI, apiAuthToken runtime.ClientAuthInfoWriter, credentialsParams params.CreateGithubCredentialsParams) (*params.ForgeCredentials, error) { createCredentialsResponse, err := apiCli.Credentials.CreateCredentials( clientCredentials.NewCreateCredentialsParams().WithBody(credentialsParams), apiAuthToken) @@ -67,7 +67,7 @@ func deleteGithubCredentials(apiCli *client.GarmAPI, apiAuthToken runtime.Client apiAuthToken) } -func updateGithubCredentials(apiCli *client.GarmAPI, apiAuthToken runtime.ClientAuthInfoWriter, credentialsID int64, credentialsParams params.UpdateGithubCredentialsParams) (*params.GithubCredentials, error) { +func updateGithubCredentials(apiCli *client.GarmAPI, apiAuthToken runtime.ClientAuthInfoWriter, credentialsID int64, credentialsParams params.UpdateGithubCredentialsParams) (*params.ForgeCredentials, error) { updateCredentialsResponse, err := apiCli.Credentials.UpdateCredentials( clientCredentials.NewUpdateCredentialsParams().WithID(credentialsID).WithBody(credentialsParams), apiAuthToken) diff --git a/test/integration/credentials_test.go b/test/integration/credentials_test.go index f7c9c691..f1594f87 100644 --- a/test/integration/credentials_test.go +++ b/test/integration/credentials_test.go @@ -199,7 +199,7 @@ func (suite *GarmSuite) TestGithubCredentialsFailsOnDuplicateName() { expectAPIStatusCode(err, 409) } -func (suite *GarmSuite) createDummyCredentials(name, endpointName string) (*params.GithubCredentials, error) { +func (suite *GarmSuite) createDummyCredentials(name, endpointName string) (*params.ForgeCredentials, error) { createCredsParams := params.CreateGithubCredentialsParams{ Name: name, Endpoint: endpointName, @@ -212,7 +212,7 @@ func (suite *GarmSuite) createDummyCredentials(name, endpointName string) (*para return suite.CreateGithubCredentials(createCredsParams) } -func (suite *GarmSuite) CreateGithubCredentials(credentialsParams params.CreateGithubCredentialsParams) (*params.GithubCredentials, error) { +func (suite *GarmSuite) CreateGithubCredentials(credentialsParams params.CreateGithubCredentialsParams) (*params.ForgeCredentials, error) { t := suite.T() t.Log("Create GitHub credentials") credentials, err := createGithubCredentials(suite.cli, suite.authToken, credentialsParams) diff --git a/util/github/client.go b/util/github/client.go index 1480561a..bcdebc13 100644 --- a/util/github/client.go +++ b/util/github/client.go @@ -477,6 +477,12 @@ func (g *githubClient) GetEntityJITConfig(ctx context.Context, instance string, func (g *githubClient) RateLimit(ctx context.Context) (*github.RateLimits, error) { limits, resp, err := g.rateLimit.Get(ctx) + if err != nil { + metrics.GithubOperationFailedCount.WithLabelValues( + "GetRateLimit", // label: operation + g.entity.LabelScope(), // label: scope + ).Inc() + } if err := parseError(resp, err); err != nil { return nil, fmt.Errorf("getting rate limit: %w", err) } @@ -491,7 +497,7 @@ func (g *githubClient) GithubBaseURL() *url.URL { return g.cli.BaseURL } -func NewRateLimitClient(ctx context.Context, credentials params.GithubCredentials) (common.RateLimitClient, error) { +func NewRateLimitClient(ctx context.Context, credentials params.ForgeCredentials) (common.RateLimitClient, error) { httpClient, err := credentials.GetHTTPClient(ctx) if err != nil { return nil, errors.Wrap(err, "fetching http client") @@ -515,12 +521,12 @@ func NewRateLimitClient(ctx context.Context, credentials params.GithubCredential return cli, nil } -func withGiteaURLs(client *github.Client, apiBaseURL, uploadBaseURL string) (*github.Client, error) { +func withGiteaURLs(client *github.Client, apiBaseURL string) (*github.Client, error) { if client == nil { return nil, errors.New("client is nil") } - if apiBaseURL == "" || uploadBaseURL == "" { + if apiBaseURL == "" { return nil, errors.New("invalid gitea URLs") } @@ -537,21 +543,8 @@ func withGiteaURLs(client *github.Client, apiBaseURL, uploadBaseURL string) (*gi parsedBaseURL.Path += "api/v1/" } - parsedUploadURL, err := url.ParseRequestURI(uploadBaseURL) - if err != nil { - return nil, errors.Wrap(err, "parsing gitea upload URL") - } - - if !strings.HasSuffix(parsedUploadURL.Path, "/") { - parsedUploadURL.Path += "/" - } - - if !strings.HasSuffix(parsedUploadURL.Path, "/api/v1/") { - parsedUploadURL.Path += "api/v1/" - } - client.BaseURL = parsedBaseURL - client.UploadURL = parsedUploadURL + client.UploadURL = parsedBaseURL return client, nil } @@ -565,15 +558,15 @@ func Client(ctx context.Context, entity params.ForgeEntity) (common.GithubClient slog.DebugContext( ctx, "creating client for entity", - "entity", entity.String(), "base_url", entity.Credentials.APIBaseURL(), - "upload_url", entity.Credentials.UploadBaseURL()) + "entity", entity.String(), "base_url", entity.Credentials.APIBaseURL, + "upload_url", entity.Credentials.UploadBaseURL) ghClient := github.NewClient(httpClient) - switch entity.Credentials.ForgeType { + switch entity.Credentials.Endpoint.EndpointType { case params.GithubEndpointType: - ghClient, err = ghClient.WithEnterpriseURLs(entity.Credentials.APIBaseURL(), entity.Credentials.UploadBaseURL()) + ghClient, err = ghClient.WithEnterpriseURLs(entity.Credentials.APIBaseURL, entity.Credentials.UploadBaseURL) case params.GiteaEndpointType: - ghClient, err = withGiteaURLs(ghClient, entity.Credentials.APIBaseURL(), entity.Credentials.UploadBaseURL()) + ghClient, err = withGiteaURLs(ghClient, entity.Credentials.APIBaseURL) } if err != nil { diff --git a/vendor/golang.org/x/mod/LICENSE b/vendor/golang.org/x/mod/LICENSE new file mode 100644 index 00000000..6a66aea5 --- /dev/null +++ b/vendor/golang.org/x/mod/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2009 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/golang.org/x/mod/PATENTS b/vendor/golang.org/x/mod/PATENTS new file mode 100644 index 00000000..73309904 --- /dev/null +++ b/vendor/golang.org/x/mod/PATENTS @@ -0,0 +1,22 @@ +Additional IP Rights Grant (Patents) + +"This implementation" means the copyrightable works distributed by +Google as part of the Go project. + +Google hereby grants to You a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable (except as stated in this section) +patent license to make, have made, use, offer to sell, sell, import, +transfer and otherwise run, modify and propagate the contents of this +implementation of Go, where such license applies only to those patent +claims, both currently owned or controlled by Google and acquired in +the future, licensable by Google that are necessarily infringed by this +implementation of Go. This grant does not include claims that would be +infringed only as a consequence of further modification of this +implementation. If you or your agent or exclusive licensee institute or +order or agree to the institution of patent litigation against any +entity (including a cross-claim or counterclaim in a lawsuit) alleging +that this implementation of Go or any code incorporated within this +implementation of Go constitutes direct or contributory patent +infringement, or inducement of patent infringement, then any patent +rights granted to you under this License for this implementation of Go +shall terminate as of the date such litigation is filed. diff --git a/vendor/golang.org/x/mod/semver/semver.go b/vendor/golang.org/x/mod/semver/semver.go new file mode 100644 index 00000000..9a2dfd33 --- /dev/null +++ b/vendor/golang.org/x/mod/semver/semver.go @@ -0,0 +1,401 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package semver implements comparison of semantic version strings. +// In this package, semantic version strings must begin with a leading "v", +// as in "v1.0.0". +// +// The general form of a semantic version string accepted by this package is +// +// vMAJOR[.MINOR[.PATCH[-PRERELEASE][+BUILD]]] +// +// where square brackets indicate optional parts of the syntax; +// MAJOR, MINOR, and PATCH are decimal integers without extra leading zeros; +// PRERELEASE and BUILD are each a series of non-empty dot-separated identifiers +// using only alphanumeric characters and hyphens; and +// all-numeric PRERELEASE identifiers must not have leading zeros. +// +// This package follows Semantic Versioning 2.0.0 (see semver.org) +// with two exceptions. First, it requires the "v" prefix. Second, it recognizes +// vMAJOR and vMAJOR.MINOR (with no prerelease or build suffixes) +// as shorthands for vMAJOR.0.0 and vMAJOR.MINOR.0. +package semver + +import "sort" + +// parsed returns the parsed form of a semantic version string. +type parsed struct { + major string + minor string + patch string + short string + prerelease string + build string +} + +// IsValid reports whether v is a valid semantic version string. +func IsValid(v string) bool { + _, ok := parse(v) + return ok +} + +// Canonical returns the canonical formatting of the semantic version v. +// It fills in any missing .MINOR or .PATCH and discards build metadata. +// Two semantic versions compare equal only if their canonical formattings +// are identical strings. +// The canonical invalid semantic version is the empty string. +func Canonical(v string) string { + p, ok := parse(v) + if !ok { + return "" + } + if p.build != "" { + return v[:len(v)-len(p.build)] + } + if p.short != "" { + return v + p.short + } + return v +} + +// Major returns the major version prefix of the semantic version v. +// For example, Major("v2.1.0") == "v2". +// If v is an invalid semantic version string, Major returns the empty string. +func Major(v string) string { + pv, ok := parse(v) + if !ok { + return "" + } + return v[:1+len(pv.major)] +} + +// MajorMinor returns the major.minor version prefix of the semantic version v. +// For example, MajorMinor("v2.1.0") == "v2.1". +// If v is an invalid semantic version string, MajorMinor returns the empty string. +func MajorMinor(v string) string { + pv, ok := parse(v) + if !ok { + return "" + } + i := 1 + len(pv.major) + if j := i + 1 + len(pv.minor); j <= len(v) && v[i] == '.' && v[i+1:j] == pv.minor { + return v[:j] + } + return v[:i] + "." + pv.minor +} + +// Prerelease returns the prerelease suffix of the semantic version v. +// For example, Prerelease("v2.1.0-pre+meta") == "-pre". +// If v is an invalid semantic version string, Prerelease returns the empty string. +func Prerelease(v string) string { + pv, ok := parse(v) + if !ok { + return "" + } + return pv.prerelease +} + +// Build returns the build suffix of the semantic version v. +// For example, Build("v2.1.0+meta") == "+meta". +// If v is an invalid semantic version string, Build returns the empty string. +func Build(v string) string { + pv, ok := parse(v) + if !ok { + return "" + } + return pv.build +} + +// Compare returns an integer comparing two versions according to +// semantic version precedence. +// The result will be 0 if v == w, -1 if v < w, or +1 if v > w. +// +// An invalid semantic version string is considered less than a valid one. +// All invalid semantic version strings compare equal to each other. +func Compare(v, w string) int { + pv, ok1 := parse(v) + pw, ok2 := parse(w) + if !ok1 && !ok2 { + return 0 + } + if !ok1 { + return -1 + } + if !ok2 { + return +1 + } + if c := compareInt(pv.major, pw.major); c != 0 { + return c + } + if c := compareInt(pv.minor, pw.minor); c != 0 { + return c + } + if c := compareInt(pv.patch, pw.patch); c != 0 { + return c + } + return comparePrerelease(pv.prerelease, pw.prerelease) +} + +// Max canonicalizes its arguments and then returns the version string +// that compares greater. +// +// Deprecated: use [Compare] instead. In most cases, returning a canonicalized +// version is not expected or desired. +func Max(v, w string) string { + v = Canonical(v) + w = Canonical(w) + if Compare(v, w) > 0 { + return v + } + return w +} + +// ByVersion implements [sort.Interface] for sorting semantic version strings. +type ByVersion []string + +func (vs ByVersion) Len() int { return len(vs) } +func (vs ByVersion) Swap(i, j int) { vs[i], vs[j] = vs[j], vs[i] } +func (vs ByVersion) Less(i, j int) bool { + cmp := Compare(vs[i], vs[j]) + if cmp != 0 { + return cmp < 0 + } + return vs[i] < vs[j] +} + +// Sort sorts a list of semantic version strings using [ByVersion]. +func Sort(list []string) { + sort.Sort(ByVersion(list)) +} + +func parse(v string) (p parsed, ok bool) { + if v == "" || v[0] != 'v' { + return + } + p.major, v, ok = parseInt(v[1:]) + if !ok { + return + } + if v == "" { + p.minor = "0" + p.patch = "0" + p.short = ".0.0" + return + } + if v[0] != '.' { + ok = false + return + } + p.minor, v, ok = parseInt(v[1:]) + if !ok { + return + } + if v == "" { + p.patch = "0" + p.short = ".0" + return + } + if v[0] != '.' { + ok = false + return + } + p.patch, v, ok = parseInt(v[1:]) + if !ok { + return + } + if len(v) > 0 && v[0] == '-' { + p.prerelease, v, ok = parsePrerelease(v) + if !ok { + return + } + } + if len(v) > 0 && v[0] == '+' { + p.build, v, ok = parseBuild(v) + if !ok { + return + } + } + if v != "" { + ok = false + return + } + ok = true + return +} + +func parseInt(v string) (t, rest string, ok bool) { + if v == "" { + return + } + if v[0] < '0' || '9' < v[0] { + return + } + i := 1 + for i < len(v) && '0' <= v[i] && v[i] <= '9' { + i++ + } + if v[0] == '0' && i != 1 { + return + } + return v[:i], v[i:], true +} + +func parsePrerelease(v string) (t, rest string, ok bool) { + // "A pre-release version MAY be denoted by appending a hyphen and + // a series of dot separated identifiers immediately following the patch version. + // Identifiers MUST comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. + // Identifiers MUST NOT be empty. Numeric identifiers MUST NOT include leading zeroes." + if v == "" || v[0] != '-' { + return + } + i := 1 + start := 1 + for i < len(v) && v[i] != '+' { + if !isIdentChar(v[i]) && v[i] != '.' { + return + } + if v[i] == '.' { + if start == i || isBadNum(v[start:i]) { + return + } + start = i + 1 + } + i++ + } + if start == i || isBadNum(v[start:i]) { + return + } + return v[:i], v[i:], true +} + +func parseBuild(v string) (t, rest string, ok bool) { + if v == "" || v[0] != '+' { + return + } + i := 1 + start := 1 + for i < len(v) { + if !isIdentChar(v[i]) && v[i] != '.' { + return + } + if v[i] == '.' { + if start == i { + return + } + start = i + 1 + } + i++ + } + if start == i { + return + } + return v[:i], v[i:], true +} + +func isIdentChar(c byte) bool { + return 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' || c == '-' +} + +func isBadNum(v string) bool { + i := 0 + for i < len(v) && '0' <= v[i] && v[i] <= '9' { + i++ + } + return i == len(v) && i > 1 && v[0] == '0' +} + +func isNum(v string) bool { + i := 0 + for i < len(v) && '0' <= v[i] && v[i] <= '9' { + i++ + } + return i == len(v) +} + +func compareInt(x, y string) int { + if x == y { + return 0 + } + if len(x) < len(y) { + return -1 + } + if len(x) > len(y) { + return +1 + } + if x < y { + return -1 + } else { + return +1 + } +} + +func comparePrerelease(x, y string) int { + // "When major, minor, and patch are equal, a pre-release version has + // lower precedence than a normal version. + // Example: 1.0.0-alpha < 1.0.0. + // Precedence for two pre-release versions with the same major, minor, + // and patch version MUST be determined by comparing each dot separated + // identifier from left to right until a difference is found as follows: + // identifiers consisting of only digits are compared numerically and + // identifiers with letters or hyphens are compared lexically in ASCII + // sort order. Numeric identifiers always have lower precedence than + // non-numeric identifiers. A larger set of pre-release fields has a + // higher precedence than a smaller set, if all of the preceding + // identifiers are equal. + // Example: 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < + // 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0." + if x == y { + return 0 + } + if x == "" { + return +1 + } + if y == "" { + return -1 + } + for x != "" && y != "" { + x = x[1:] // skip - or . + y = y[1:] // skip - or . + var dx, dy string + dx, x = nextIdent(x) + dy, y = nextIdent(y) + if dx != dy { + ix := isNum(dx) + iy := isNum(dy) + if ix != iy { + if ix { + return -1 + } else { + return +1 + } + } + if ix { + if len(dx) < len(dy) { + return -1 + } + if len(dx) > len(dy) { + return +1 + } + } + if dx < dy { + return -1 + } else { + return +1 + } + } + } + if x == "" { + return -1 + } else { + return +1 + } +} + +func nextIdent(x string) (dx, rest string) { + i := 0 + for i < len(x) && x[i] != '.' { + i++ + } + return x[:i], x[i:] +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 5cb70bb1..dbd42ce3 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -286,6 +286,9 @@ golang.org/x/crypto/chacha20poly1305 golang.org/x/crypto/hkdf golang.org/x/crypto/internal/alias golang.org/x/crypto/internal/poly1305 +# golang.org/x/mod v0.17.0 +## explicit; go 1.18 +golang.org/x/mod/semver # golang.org/x/net v0.40.0 ## explicit; go 1.23.0 golang.org/x/net/internal/socks diff --git a/workers/cache/cache.go b/workers/cache/cache.go index ce23d269..918b3438 100644 --- a/workers/cache/cache.go +++ b/workers/cache/cache.go @@ -138,7 +138,7 @@ func (w *Worker) loadAllInstances() error { return nil } -func (w *Worker) loadAllCredentials() error { +func (w *Worker) loadAllGithubCredentials() error { creds, err := w.store.ListGithubCredentials(w.ctx) if err != nil { return fmt.Errorf("listing github credentials: %w", err) @@ -150,6 +150,18 @@ func (w *Worker) loadAllCredentials() error { return nil } +func (w *Worker) loadAllGiteaCredentials() error { + creds, err := w.store.ListGiteaCredentials(w.ctx) + if err != nil { + return fmt.Errorf("listing gitea credentials: %w", err) + } + + for _, cred := range creds { + cache.SetGiteaCredentials(cred) + } + return nil +} + func (w *Worker) waitForErrorGroupOrContextCancelled(g *errgroup.Group) error { if g == nil { return nil @@ -182,6 +194,20 @@ func (w *Worker) Start() error { g, _ := errgroup.WithContext(w.ctx) + g.Go(func() error { + if err := w.loadAllGithubCredentials(); err != nil { + return fmt.Errorf("loading all github credentials: %w", err) + } + return nil + }) + + g.Go(func() error { + if err := w.loadAllGiteaCredentials(); err != nil { + return fmt.Errorf("loading all gitea credentials: %w", err) + } + return nil + }) + g.Go(func() error { if err := w.loadAllEntities(); err != nil { return fmt.Errorf("loading all entities: %w", err) @@ -196,13 +222,6 @@ func (w *Worker) Start() error { return nil }) - g.Go(func() error { - if err := w.loadAllCredentials(); err != nil { - return fmt.Errorf("loading all credentials: %w", err) - } - return nil - }) - if err := w.waitForErrorGroupOrContextCancelled(g); err != nil { return fmt.Errorf("waiting for error group: %w", err) } @@ -360,7 +379,7 @@ func (w *Worker) handleInstanceEvent(event common.ChangePayload) { } func (w *Worker) handleCredentialsEvent(event common.ChangePayload) { - credentials, ok := event.Payload.(params.GithubCredentials) + credentials, ok := event.Payload.(params.ForgeCredentials) if !ok { slog.DebugContext(w.ctx, "invalid payload type for credentials event", "payload", event.Payload) return diff --git a/workers/cache/gitea_tools.go b/workers/cache/gitea_tools.go new file mode 100644 index 00000000..8b2fc758 --- /dev/null +++ b/workers/cache/gitea_tools.go @@ -0,0 +1,152 @@ +package cache + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "time" + + commonParams "github.com/cloudbase/garm-provider-common/params" + "golang.org/x/mod/semver" +) + +const ( + // GiteaRunnerReleasesURL is the public API URL that returns a json of all Gitea runner releases. + // By default it returns the last 10 releases, which is enough for our needs. + GiteaRunnerReleasesURL = "https://gitea.com/api/v1/repos/gitea/act_runner/releases" + // GiteaRunnerMinimumVersion is the minimum version we need in order to support ephemeral runners. + GiteaRunnerMinimumVersion = "v0.2.12" +) + +var nightlyActRunner = GiteaEntityTool{ + TagName: "nightly", + Name: "nightly", + TarballURL: "https://gitea.com/gitea/act_runner/archive/main.tar.gz", + Assets: []GiteaToolsAssets{ + { + Name: "act_runner-nightly-linux-amd64.xz", + DownloadURL: "https://dl.gitea.com/act_runner/nightly/act_runner-nightly-linux-amd64.xz", + }, + { + Name: "act_runner-nightly-linux-arm64.xz", + DownloadURL: "https://dl.gitea.com/act_runner/nightly/act_runner-nightly-linux-arm64.xz", + }, + { + Name: "act_runner-nightly-windows-amd64.exe.xz", + DownloadURL: "https://dl.gitea.com/act_runner/nightly/act_runner-nightly-windows-amd64.exe.xz", + }, + }, +} + +type GiteaToolsAssets struct { + ID uint `json:"id"` + Name string `json:"name"` + Size uint `json:"size"` + DownloadCount uint `json:"download_count"` + CreatedAt time.Time `json:"created_at"` + UUID string `json:"uuid"` + DownloadURL string `json:"browser_download_url"` +} + +func (g GiteaToolsAssets) GetOS() *string { + if g.Name == "" { + return nil + } + + parts := strings.SplitN(g.Name, "-", 4) + if len(parts) != 4 { + return nil + } + + os := parts[2] + return &os +} + +func (g GiteaToolsAssets) GetArch() *string { + if g.Name == "" { + return nil + } + + parts := strings.SplitN(g.Name, "-", 4) + if len(parts) != 4 { + return nil + } + + archParts := strings.SplitN(parts[3], ".", 2) + if len(archParts) == 0 { + return nil + } + arch := archParts[0] + return &arch +} + +type GiteaEntityTool struct { + // TagName is the semver version of the release. + TagName string `json:"tag_name"` + Name string `json:"name"` + TarballURL string `json:"tarball_url"` + Assets []GiteaToolsAssets `json:"assets"` +} + +type GiteaEntityTools []GiteaEntityTool + +func (g GiteaEntityTools) GetLatestVersion() string { + if len(g) == 0 { + return "" + } + return g[0].TagName +} + +func (g GiteaEntityTools) MinimumVersion() (GiteaEntityTool, bool) { + if len(g) == 0 { + return GiteaEntityTool{}, false + } + for _, tool := range g { + if semver.Compare(tool.TagName, GiteaRunnerMinimumVersion) >= 0 { + return tool, true + } + } + return GiteaEntityTool{}, false +} + +func getTools() ([]commonParams.RunnerApplicationDownload, error) { + resp, err := http.Get(GiteaRunnerReleasesURL) + if err != nil { + return nil, err + } + defer resp.Body.Close() + data, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + var tools GiteaEntityTools + err = json.Unmarshal(data, &tools) + if err != nil { + return nil, err + } + + if len(tools) == 0 { + return nil, fmt.Errorf("no tools found") + } + + latest, ok := tools.MinimumVersion() + if !ok { + latest = nightlyActRunner + } + + ret := []commonParams.RunnerApplicationDownload{} + + for _, asset := range latest.Assets { + ret = append(ret, commonParams.RunnerApplicationDownload{ + OS: asset.GetOS(), + Architecture: asset.GetArch(), + DownloadURL: &asset.DownloadURL, + Filename: &asset.Name, + }) + } + + return ret, nil +} diff --git a/workers/cache/tool_cache.go b/workers/cache/tool_cache.go index 7d8d5737..d3c74673 100644 --- a/workers/cache/tool_cache.go +++ b/workers/cache/tool_cache.go @@ -49,7 +49,14 @@ func (t *toolsUpdater) Start() error { t.running = true t.quit = make(chan struct{}) - go t.loop() + slog.DebugContext(t.ctx, "starting tools updater", "entity", t.entity.String(), "forge_type", t.entity.Credentials) + + switch t.entity.Credentials.ForgeType { + case params.GithubEndpointType: + go t.loop() + case params.GiteaEndpointType: + go t.giteaUpdateLoop() + } return nil } @@ -68,7 +75,7 @@ func (t *toolsUpdater) Stop() error { } func (t *toolsUpdater) updateTools() error { - slog.DebugContext(t.ctx, "updating tools", "entity", t.entity.String()) + slog.DebugContext(t.ctx, "updating tools", "entity", t.entity.String(), "forge_type", t.entity.Credentials.ForgeType) entity, ok := cache.GetEntity(t.entity.ID) if !ok { return fmt.Errorf("getting entity from cache: %s", t.entity.ID) @@ -98,12 +105,69 @@ func (t *toolsUpdater) Reset() { return } + if t.entity.Credentials.ForgeType == params.GiteaEndpointType { + // no need to reset the gitea tools updater when credentials + // are updated. + return + } + if t.reset != nil { close(t.reset) t.reset = nil } } +func (t *toolsUpdater) sleepWithCancel(sleepTime time.Duration) (canceled bool) { + ticker := time.NewTicker(sleepTime) + defer ticker.Stop() + + select { + case <-ticker.C: + return false + case <-t.quit: + case <-t.ctx.Done(): + } + return true +} + +// giteaUpdateLoop updates tools for gitea. The act runner can be downloaded +// without a token, unlike the github tools, which for GHES require a token. +func (t *toolsUpdater) giteaUpdateLoop() { + defer t.Stop() + + // add some jitter. When spinning up multiple entities, we add + // jitter to prevent stampeeding herd. + randInt, err := rand.Int(rand.Reader, big.NewInt(3000)) + if err != nil { + randInt = big.NewInt(0) + } + t.sleepWithCancel(time.Duration(randInt.Int64()) * time.Millisecond) + tools, err := getTools() + if err == nil { + cache.SetGithubToolsCache(t.entity, tools) + } + + // Once every 3 hours should be enough. Tools don't expire. + ticker := time.NewTicker(3 * time.Hour) + + for { + select { + case <-t.quit: + slog.DebugContext(t.ctx, "stopping tools updater") + return + case <-t.ctx.Done(): + return + case <-ticker.C: + tools, err := getTools() + if err != nil { + slog.DebugContext(t.ctx, "failed to update gitea tools", "error", err) + continue + } + cache.SetGithubToolsCache(t.entity, tools) + } + } +} + func (t *toolsUpdater) loop() { defer t.Stop() @@ -113,7 +177,7 @@ func (t *toolsUpdater) loop() { if err != nil { randInt = big.NewInt(0) } - time.Sleep(time.Duration(randInt.Int64()) * time.Millisecond) + t.sleepWithCancel(time.Duration(randInt.Int64()) * time.Millisecond) var resetTime time.Time now := time.Now().UTC() diff --git a/workers/entity/controller.go b/workers/entity/controller.go index db353f0e..2cb910b3 100644 --- a/workers/entity/controller.go +++ b/workers/entity/controller.go @@ -215,6 +215,7 @@ func (c *Controller) Stop() error { c.running = false close(c.quit) c.consumer.Close() + slog.DebugContext(c.ctx, "stopped entity controller", "entity", c.consumerID) return nil } diff --git a/workers/entity/worker.go b/workers/entity/worker.go index 7f0f79e6..597d5797 100644 --- a/workers/entity/worker.go +++ b/workers/entity/worker.go @@ -70,6 +70,7 @@ func (w *Worker) Stop() error { w.running = false close(w.quit) w.consumer.Close() + slog.DebugContext(w.ctx, "entity worker stopped", "entity", w.consumerID) return nil } diff --git a/workers/entity/worker_watcher.go b/workers/entity/worker_watcher.go index 04e20a65..f445b73d 100644 --- a/workers/entity/worker_watcher.go +++ b/workers/entity/worker_watcher.go @@ -63,12 +63,11 @@ func (w *Worker) handleEntityEventPayload(event dbCommon.ChangePayload) { } func (w *Worker) handleEntityCredentialsEventPayload(event dbCommon.ChangePayload) { - var credsGetter params.ForgeCredentialsGetter + var creds params.ForgeCredentials var ok bool - switch event.EntityType { case dbCommon.GithubCredentialsEntityType: - credsGetter, ok = event.Payload.(params.GithubCredentials) + creds, ok = event.Payload.(params.ForgeCredentials) default: slog.ErrorContext(w.ctx, "invalid entity type", "entity_type", event.EntityType) return @@ -78,7 +77,7 @@ func (w *Worker) handleEntityCredentialsEventPayload(event dbCommon.ChangePayloa return } - credentials := credsGetter.GetForgeCredentials() + credentials := creds switch event.Operation { case dbCommon.UpdateOperation: diff --git a/workers/provider/instance_manager.go b/workers/provider/instance_manager.go index 9ba94553..47e875a0 100644 --- a/workers/provider/instance_manager.go +++ b/workers/provider/instance_manager.go @@ -167,7 +167,7 @@ func (i *instanceManager) handleCreateInstanceInProvider(instance params.Instanc ExtraSpecs: i.scaleSet.ExtraSpecs, // This is temporary. We need to extend providers to know about scale sets. PoolID: i.pseudoPoolID(), - CACertBundle: entity.Credentials.CABundle(), + CACertBundle: entity.Credentials.CABundle, GitHubRunnerGroup: i.scaleSet.GitHubRunnerGroup, JitConfigEnabled: true, } diff --git a/workers/scaleset/controller.go b/workers/scaleset/controller.go index 45dfbfa3..e28eb7ee 100644 --- a/workers/scaleset/controller.go +++ b/workers/scaleset/controller.go @@ -137,7 +137,7 @@ func (c *Controller) Stop() error { c.running = false close(c.quit) c.consumer.Close() - + slog.DebugContext(c.ctx, "stopped scale set controller", "entity", c.Entity.String()) return nil } diff --git a/workers/scaleset/scaleset.go b/workers/scaleset/scaleset.go index 097a8680..1090388d 100644 --- a/workers/scaleset/scaleset.go +++ b/workers/scaleset/scaleset.go @@ -910,7 +910,7 @@ func (w *Worker) handleAutoScale() { } if !hasTools { - time.Sleep(1 * time.Second) + w.sleepWithCancel(1 * time.Second) continue }