Add github endpoint API endpoint and CLI code

Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
This commit is contained in:
Gabriel Adrian Samfira 2024-04-18 16:50:46 +00:00
parent 257fb0b09a
commit 77ecb16166
27 changed files with 2807 additions and 73 deletions

View file

@ -102,7 +102,10 @@ func (a *APIController) handleWorkflowJobEvent(ctx context.Context, w http.Respo
handleError(ctx, w, gErrors.NewBadRequestError("invalid post body: %s", err))
return
}
slog.Info("received webhook", "body", string(body))
for k, v := range r.Header {
slog.InfoContext(ctx, "header", "key", k, "value", v)
}
signature := r.Header.Get("X-Hub-Signature-256")
hookType := r.Header.Get("X-Github-Hook-Installation-Target-Type")
@ -329,27 +332,6 @@ func (a *APIController) FirstRunHandler(w http.ResponseWriter, r *http.Request)
}
}
// swagger:route GET /credentials credentials ListCredentials
//
// List all credentials.
//
// Responses:
// 200: Credentials
// 400: APIErrorResponse
func (a *APIController) ListCredentials(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
creds, err := a.r.ListCredentials(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 GET /providers providers ListProviders
//
// List all providers.

View file

@ -0,0 +1,28 @@
package controllers
import (
"encoding/json"
"log/slog"
"net/http"
)
// swagger:route GET /credentials credentials ListCredentials
//
// List all credentials.
//
// Responses:
// 200: Credentials
// 400: APIErrorResponse
func (a *APIController) ListCredentials(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
creds, err := a.r.ListCredentials(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")
}
}

View file

@ -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 /github/endpoints endpoints CreateGithubEndpoint
//
// Create a GitHub Endpoint.
//
// Parameters:
// + name: Body
// description: Parameters used when creating a GitHub endpoint.
// type: CreateGithubEndpointParams
// in: body
// required: true
//
// Responses:
// 200: GithubEndpoint
// default: APIErrorResponse
func (a *APIController) CreateGithubEndpoint(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var params params.CreateGithubEndpointParams
if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to decode request")
handleError(ctx, w, gErrors.ErrBadRequest)
return
}
endpoint, err := a.r.CreateGithubEndpoint(ctx, params)
if err != nil {
slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to create 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")
}
}
// swagger:route GET /github/endpoints endpoints ListGithubEndpoints
//
// List all GitHub Endpoints.
//
// Responses:
// 200: GithubEndpoints
// default: APIErrorResponse
func (a *APIController) ListGithubEndpoints(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
endpoints, err := a.r.ListGithubEndpoints(ctx)
if err != nil {
slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to list GitHub 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 /github/endpoints/{name} endpoints GetGithubEndpoint
//
// Get a GitHub Endpoint.
//
// Parameters:
// + name: name
// description: The name of the GitHub endpoint.
// type: string
// in: path
// required: true
//
// Responses:
// 200: GithubEndpoint
// default: APIErrorResponse
func (a *APIController) GetGithubEndpoint(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.GetGithubEndpoint(ctx, name)
if err != nil {
slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to get 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")
}
}
// swagger:route DELETE /github/endpoints/{name} endpoints DeleteGithubEndpoint
//
// Delete a GitHub Endpoint.
//
// Parameters:
// + name: name
// description: The name of the GitHub endpoint.
// type: string
// in: path
// required: true
//
// Responses:
// default: APIErrorResponse
func (a *APIController) DeleteGithubEndpoint(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.DeleteGithubEndpoint(ctx, name); err != nil {
slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to delete GitHub endpoint")
handleError(ctx, w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
// swagger:route PUT /github/endpoints/{name} endpoints UpdateGithubEndpoint
//
// Update a GitHub Endpoint.
//
// Parameters:
// + name: name
// description: The name of the GitHub endpoint.
// type: string
// in: path
// required: true
// + name: Body
// description: Parameters used when updating a GitHub endpoint.
// type: UpdateGithubEndpointParams
// in: body
// required: true
//
// Responses:
// 200: GithubEndpoint
// default: APIErrorResponse
func (a *APIController) UpdateGithubEndpoint(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.UpdateGithubEndpointParams
if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
slog.With(slog.Any("error", err)).ErrorContext(ctx, "failed to decode request")
handleError(ctx, w, gErrors.ErrBadRequest)
return
}
endpoint, err := a.r.UpdateGithubEndpoint(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")
}
}

View file

@ -339,9 +339,11 @@ func NewAPIRouter(han *controllers.APIController, authMiddleware, initMiddleware
apiRouter.Handle("/enterprises/", http.HandlerFunc(han.CreateEnterpriseHandler)).Methods("POST", "OPTIONS")
apiRouter.Handle("/enterprises", http.HandlerFunc(han.CreateEnterpriseHandler)).Methods("POST", "OPTIONS")
// Credentials and providers
// Credentials
apiRouter.Handle("/credentials/", http.HandlerFunc(han.ListCredentials)).Methods("GET", "OPTIONS")
apiRouter.Handle("/credentials", http.HandlerFunc(han.ListCredentials)).Methods("GET", "OPTIONS")
// Providers
apiRouter.Handle("/providers/", http.HandlerFunc(han.ListProviders)).Methods("GET", "OPTIONS")
apiRouter.Handle("/providers", http.HandlerFunc(han.ListProviders)).Methods("GET", "OPTIONS")
@ -349,6 +351,25 @@ func NewAPIRouter(han *controllers.APIController, authMiddleware, initMiddleware
apiRouter.Handle("/controller-info/", http.HandlerFunc(han.ControllerInfoHandler)).Methods("GET", "OPTIONS")
apiRouter.Handle("/controller-info", http.HandlerFunc(han.ControllerInfoHandler)).Methods("GET", "OPTIONS")
//////////////////////
// Github Endpoints //
//////////////////////
// Create Github Endpoint
apiRouter.Handle("/github/endpoints/", http.HandlerFunc(han.CreateGithubEndpoint)).Methods("POST", "OPTIONS")
apiRouter.Handle("/github/endpoints", http.HandlerFunc(han.CreateGithubEndpoint)).Methods("POST", "OPTIONS")
// List Github Endpoints
apiRouter.Handle("/github/endpoints/", http.HandlerFunc(han.ListGithubEndpoints)).Methods("GET", "OPTIONS")
apiRouter.Handle("/github/endpoints", http.HandlerFunc(han.ListGithubEndpoints)).Methods("GET", "OPTIONS")
// Get Github Endpoint
apiRouter.Handle("/github/endpoints/{name}/", http.HandlerFunc(han.GetGithubEndpoint)).Methods("GET", "OPTIONS")
apiRouter.Handle("/github/endpoints/{name}", http.HandlerFunc(han.GetGithubEndpoint)).Methods("GET", "OPTIONS")
// Delete Github Endpoint
apiRouter.Handle("/github/endpoints/{name}/", http.HandlerFunc(han.DeleteGithubEndpoint)).Methods("DELETE", "OPTIONS")
apiRouter.Handle("/github/endpoints/{name}", http.HandlerFunc(han.DeleteGithubEndpoint)).Methods("DELETE", "OPTIONS")
// Update Github Endpoint
apiRouter.Handle("/github/endpoints/{name}/", http.HandlerFunc(han.UpdateGithubEndpoint)).Methods("PUT", "OPTIONS")
apiRouter.Handle("/github/endpoints/{name}", http.HandlerFunc(han.UpdateGithubEndpoint)).Methods("PUT", "OPTIONS")
// Websocket log writer
apiRouter.Handle("/{ws:ws\\/?}", http.HandlerFunc(han.WSHandler)).Methods("GET")

View file

@ -227,3 +227,40 @@ definitions:
import:
package: github.com/cloudbase/garm/apiserver/params
alias: apiserver_params
CreateInstanceParams:
type: object
x-go-type:
type: CreateInstanceParams
import:
package: github.com/cloudbase/garm/params
alias: garm_params
UpdateGithubEndpointParams:
type: object
x-go-type:
type: UpdateGithubEndpointParams
import:
package: github.com/cloudbase/garm/params
alias: garm_params
GithubEndpoint:
type: object
x-go-type:
type: GithubEndpoint
import:
package: github.com/cloudbase/garm/params
alias: garm_params
GithubEndpoints:
type: array
x-go-type:
type: GithubEndpoints
import:
package: github.com/cloudbase/garm/params
alias: garm_params
items:
$ref: '#/definitions/GithubEndpoint'
CreateGithubEndpointParams:
type: object
x-go-type:
type: CreateGithubEndpointParams
import:
package: github.com/cloudbase/garm/params
alias: garm_params

View file

@ -23,6 +23,20 @@ definitions:
alias: garm_params
package: github.com/cloudbase/garm/params
type: CreateEnterpriseParams
CreateGithubEndpointParams:
type: object
x-go-type:
import:
alias: garm_params
package: github.com/cloudbase/garm/params
type: CreateGithubEndpointParams
CreateInstanceParams:
type: object
x-go-type:
import:
alias: garm_params
package: github.com/cloudbase/garm/params
type: CreateInstanceParams
CreateOrgParams:
type: object
x-go-type:
@ -76,6 +90,22 @@ definitions:
alias: garm_params
package: github.com/cloudbase/garm/params
type: GithubCredentials
GithubEndpoint:
type: object
x-go-type:
import:
alias: garm_params
package: github.com/cloudbase/garm/params
type: GithubEndpoint
GithubEndpoints:
items:
$ref: '#/definitions/GithubEndpoint'
type: array
x-go-type:
import:
alias: garm_params
package: github.com/cloudbase/garm/params
type: GithubEndpoints
HookInfo:
type: object
x-go-type:
@ -214,6 +244,13 @@ definitions:
alias: garm_params
package: github.com/cloudbase/garm/params
type: UpdateEntityParams
UpdateGithubEndpointParams:
type: object
x-go-type:
import:
alias: garm_params
package: github.com/cloudbase/garm/params
type: UpdateGithubEndpointParams
UpdatePoolParams:
type: object
x-go-type:
@ -573,6 +610,109 @@ paths:
summary: Initialize the first run of the controller.
tags:
- first-run
/github/endpoints:
get:
operationId: ListGithubEndpoints
responses:
"200":
description: GithubEndpoints
schema:
$ref: '#/definitions/GithubEndpoints'
default:
description: APIErrorResponse
schema:
$ref: '#/definitions/APIErrorResponse'
summary: List all GitHub Endpoints.
tags:
- endpoints
post:
operationId: CreateGithubEndpoint
parameters:
- description: Parameters used when creating a GitHub endpoint.
in: body
name: Body
required: true
schema:
$ref: '#/definitions/CreateGithubEndpointParams'
description: Parameters used when creating a GitHub endpoint.
type: object
responses:
"200":
description: GithubEndpoint
schema:
$ref: '#/definitions/GithubEndpoint'
default:
description: APIErrorResponse
schema:
$ref: '#/definitions/APIErrorResponse'
summary: Create a GitHub Endpoint.
tags:
- endpoints
/github/endpoints/{name}:
delete:
operationId: DeleteGithubEndpoint
parameters:
- description: The name of the GitHub endpoint.
in: path
name: name
required: true
type: string
responses:
default:
description: APIErrorResponse
schema:
$ref: '#/definitions/APIErrorResponse'
summary: Delete a GitHub Endpoint.
tags:
- endpoints
get:
operationId: GetGithubEndpoint
parameters:
- description: The name of the GitHub endpoint.
in: path
name: name
required: true
type: string
responses:
"200":
description: GithubEndpoint
schema:
$ref: '#/definitions/GithubEndpoint'
default:
description: APIErrorResponse
schema:
$ref: '#/definitions/APIErrorResponse'
summary: Get a GitHub Endpoint.
tags:
- endpoints
put:
operationId: UpdateGithubEndpoint
parameters:
- description: The name of the GitHub endpoint.
in: path
name: name
required: true
type: string
- description: Parameters used when updating a GitHub endpoint.
in: body
name: Body
required: true
schema:
$ref: '#/definitions/UpdateGithubEndpointParams'
description: Parameters used when updating a GitHub endpoint.
type: object
responses:
"200":
description: GithubEndpoint
schema:
$ref: '#/definitions/GithubEndpoint'
default:
description: APIErrorResponse
schema:
$ref: '#/definitions/APIErrorResponse'
summary: Update a GitHub Endpoint.
tags:
- endpoints
/instances:
get:
operationId: ListInstances

View file

@ -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"
)
// NewCreateGithubEndpointParams creates a new CreateGithubEndpointParams 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 NewCreateGithubEndpointParams() *CreateGithubEndpointParams {
return &CreateGithubEndpointParams{
timeout: cr.DefaultTimeout,
}
}
// NewCreateGithubEndpointParamsWithTimeout creates a new CreateGithubEndpointParams object
// with the ability to set a timeout on a request.
func NewCreateGithubEndpointParamsWithTimeout(timeout time.Duration) *CreateGithubEndpointParams {
return &CreateGithubEndpointParams{
timeout: timeout,
}
}
// NewCreateGithubEndpointParamsWithContext creates a new CreateGithubEndpointParams object
// with the ability to set a context for a request.
func NewCreateGithubEndpointParamsWithContext(ctx context.Context) *CreateGithubEndpointParams {
return &CreateGithubEndpointParams{
Context: ctx,
}
}
// NewCreateGithubEndpointParamsWithHTTPClient creates a new CreateGithubEndpointParams object
// with the ability to set a custom HTTPClient for a request.
func NewCreateGithubEndpointParamsWithHTTPClient(client *http.Client) *CreateGithubEndpointParams {
return &CreateGithubEndpointParams{
HTTPClient: client,
}
}
/*
CreateGithubEndpointParams contains all the parameters to send to the API endpoint
for the create github endpoint operation.
Typically these are written to a http.Request.
*/
type CreateGithubEndpointParams struct {
/* Body.
Parameters used when creating a GitHub endpoint.
*/
Body garm_params.CreateGithubEndpointParams
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the create github endpoint params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *CreateGithubEndpointParams) WithDefaults() *CreateGithubEndpointParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the create github endpoint params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *CreateGithubEndpointParams) SetDefaults() {
// no default values defined for this parameter
}
// WithTimeout adds the timeout to the create github endpoint params
func (o *CreateGithubEndpointParams) WithTimeout(timeout time.Duration) *CreateGithubEndpointParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the create github endpoint params
func (o *CreateGithubEndpointParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the create github endpoint params
func (o *CreateGithubEndpointParams) WithContext(ctx context.Context) *CreateGithubEndpointParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the create github endpoint params
func (o *CreateGithubEndpointParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the create github endpoint params
func (o *CreateGithubEndpointParams) WithHTTPClient(client *http.Client) *CreateGithubEndpointParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the create github endpoint params
func (o *CreateGithubEndpointParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithBody adds the body to the create github endpoint params
func (o *CreateGithubEndpointParams) WithBody(body garm_params.CreateGithubEndpointParams) *CreateGithubEndpointParams {
o.SetBody(body)
return o
}
// SetBody adds the body to the create github endpoint params
func (o *CreateGithubEndpointParams) SetBody(body garm_params.CreateGithubEndpointParams) {
o.Body = body
}
// WriteToRequest writes these params to a swagger request
func (o *CreateGithubEndpointParams) 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
}

View file

@ -0,0 +1,179 @@
// 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 (
"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"
)
// CreateGithubEndpointReader is a Reader for the CreateGithubEndpoint structure.
type CreateGithubEndpointReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *CreateGithubEndpointReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewCreateGithubEndpointOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
default:
result := NewCreateGithubEndpointDefault(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
}
}
// NewCreateGithubEndpointOK creates a CreateGithubEndpointOK with default headers values
func NewCreateGithubEndpointOK() *CreateGithubEndpointOK {
return &CreateGithubEndpointOK{}
}
/*
CreateGithubEndpointOK describes a response with status code 200, with default header values.
GithubEndpoint
*/
type CreateGithubEndpointOK struct {
Payload garm_params.GithubEndpoint
}
// IsSuccess returns true when this create github endpoint o k response has a 2xx status code
func (o *CreateGithubEndpointOK) IsSuccess() bool {
return true
}
// IsRedirect returns true when this create github endpoint o k response has a 3xx status code
func (o *CreateGithubEndpointOK) IsRedirect() bool {
return false
}
// IsClientError returns true when this create github endpoint o k response has a 4xx status code
func (o *CreateGithubEndpointOK) IsClientError() bool {
return false
}
// IsServerError returns true when this create github endpoint o k response has a 5xx status code
func (o *CreateGithubEndpointOK) IsServerError() bool {
return false
}
// IsCode returns true when this create github endpoint o k response a status code equal to that given
func (o *CreateGithubEndpointOK) IsCode(code int) bool {
return code == 200
}
// Code gets the status code for the create github endpoint o k response
func (o *CreateGithubEndpointOK) Code() int {
return 200
}
func (o *CreateGithubEndpointOK) Error() string {
return fmt.Sprintf("[POST /github/endpoints][%d] createGithubEndpointOK %+v", 200, o.Payload)
}
func (o *CreateGithubEndpointOK) String() string {
return fmt.Sprintf("[POST /github/endpoints][%d] createGithubEndpointOK %+v", 200, o.Payload)
}
func (o *CreateGithubEndpointOK) GetPayload() garm_params.GithubEndpoint {
return o.Payload
}
func (o *CreateGithubEndpointOK) 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
}
// NewCreateGithubEndpointDefault creates a CreateGithubEndpointDefault with default headers values
func NewCreateGithubEndpointDefault(code int) *CreateGithubEndpointDefault {
return &CreateGithubEndpointDefault{
_statusCode: code,
}
}
/*
CreateGithubEndpointDefault describes a response with status code -1, with default header values.
APIErrorResponse
*/
type CreateGithubEndpointDefault struct {
_statusCode int
Payload apiserver_params.APIErrorResponse
}
// IsSuccess returns true when this create github endpoint default response has a 2xx status code
func (o *CreateGithubEndpointDefault) IsSuccess() bool {
return o._statusCode/100 == 2
}
// IsRedirect returns true when this create github endpoint default response has a 3xx status code
func (o *CreateGithubEndpointDefault) IsRedirect() bool {
return o._statusCode/100 == 3
}
// IsClientError returns true when this create github endpoint default response has a 4xx status code
func (o *CreateGithubEndpointDefault) IsClientError() bool {
return o._statusCode/100 == 4
}
// IsServerError returns true when this create github endpoint default response has a 5xx status code
func (o *CreateGithubEndpointDefault) IsServerError() bool {
return o._statusCode/100 == 5
}
// IsCode returns true when this create github endpoint default response a status code equal to that given
func (o *CreateGithubEndpointDefault) IsCode(code int) bool {
return o._statusCode == code
}
// Code gets the status code for the create github endpoint default response
func (o *CreateGithubEndpointDefault) Code() int {
return o._statusCode
}
func (o *CreateGithubEndpointDefault) Error() string {
return fmt.Sprintf("[POST /github/endpoints][%d] CreateGithubEndpoint default %+v", o._statusCode, o.Payload)
}
func (o *CreateGithubEndpointDefault) String() string {
return fmt.Sprintf("[POST /github/endpoints][%d] CreateGithubEndpoint default %+v", o._statusCode, o.Payload)
}
func (o *CreateGithubEndpointDefault) GetPayload() apiserver_params.APIErrorResponse {
return o.Payload
}
func (o *CreateGithubEndpointDefault) 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
}

View file

@ -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"
)
// NewDeleteGithubEndpointParams creates a new DeleteGithubEndpointParams 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 NewDeleteGithubEndpointParams() *DeleteGithubEndpointParams {
return &DeleteGithubEndpointParams{
timeout: cr.DefaultTimeout,
}
}
// NewDeleteGithubEndpointParamsWithTimeout creates a new DeleteGithubEndpointParams object
// with the ability to set a timeout on a request.
func NewDeleteGithubEndpointParamsWithTimeout(timeout time.Duration) *DeleteGithubEndpointParams {
return &DeleteGithubEndpointParams{
timeout: timeout,
}
}
// NewDeleteGithubEndpointParamsWithContext creates a new DeleteGithubEndpointParams object
// with the ability to set a context for a request.
func NewDeleteGithubEndpointParamsWithContext(ctx context.Context) *DeleteGithubEndpointParams {
return &DeleteGithubEndpointParams{
Context: ctx,
}
}
// NewDeleteGithubEndpointParamsWithHTTPClient creates a new DeleteGithubEndpointParams object
// with the ability to set a custom HTTPClient for a request.
func NewDeleteGithubEndpointParamsWithHTTPClient(client *http.Client) *DeleteGithubEndpointParams {
return &DeleteGithubEndpointParams{
HTTPClient: client,
}
}
/*
DeleteGithubEndpointParams contains all the parameters to send to the API endpoint
for the delete github endpoint operation.
Typically these are written to a http.Request.
*/
type DeleteGithubEndpointParams struct {
/* Name.
The name of the GitHub endpoint.
*/
Name string
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the delete github endpoint params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *DeleteGithubEndpointParams) WithDefaults() *DeleteGithubEndpointParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the delete github endpoint params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *DeleteGithubEndpointParams) SetDefaults() {
// no default values defined for this parameter
}
// WithTimeout adds the timeout to the delete github endpoint params
func (o *DeleteGithubEndpointParams) WithTimeout(timeout time.Duration) *DeleteGithubEndpointParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the delete github endpoint params
func (o *DeleteGithubEndpointParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the delete github endpoint params
func (o *DeleteGithubEndpointParams) WithContext(ctx context.Context) *DeleteGithubEndpointParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the delete github endpoint params
func (o *DeleteGithubEndpointParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the delete github endpoint params
func (o *DeleteGithubEndpointParams) WithHTTPClient(client *http.Client) *DeleteGithubEndpointParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the delete github endpoint params
func (o *DeleteGithubEndpointParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithName adds the name to the delete github endpoint params
func (o *DeleteGithubEndpointParams) WithName(name string) *DeleteGithubEndpointParams {
o.SetName(name)
return o
}
// SetName adds the name to the delete github endpoint params
func (o *DeleteGithubEndpointParams) SetName(name string) {
o.Name = name
}
// WriteToRequest writes these params to a swagger request
func (o *DeleteGithubEndpointParams) 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
}

View file

@ -0,0 +1,103 @@
// 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 (
"fmt"
"io"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
apiserver_params "github.com/cloudbase/garm/apiserver/params"
)
// DeleteGithubEndpointReader is a Reader for the DeleteGithubEndpoint structure.
type DeleteGithubEndpointReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *DeleteGithubEndpointReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
result := NewDeleteGithubEndpointDefault(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
}
// NewDeleteGithubEndpointDefault creates a DeleteGithubEndpointDefault with default headers values
func NewDeleteGithubEndpointDefault(code int) *DeleteGithubEndpointDefault {
return &DeleteGithubEndpointDefault{
_statusCode: code,
}
}
/*
DeleteGithubEndpointDefault describes a response with status code -1, with default header values.
APIErrorResponse
*/
type DeleteGithubEndpointDefault struct {
_statusCode int
Payload apiserver_params.APIErrorResponse
}
// IsSuccess returns true when this delete github endpoint default response has a 2xx status code
func (o *DeleteGithubEndpointDefault) IsSuccess() bool {
return o._statusCode/100 == 2
}
// IsRedirect returns true when this delete github endpoint default response has a 3xx status code
func (o *DeleteGithubEndpointDefault) IsRedirect() bool {
return o._statusCode/100 == 3
}
// IsClientError returns true when this delete github endpoint default response has a 4xx status code
func (o *DeleteGithubEndpointDefault) IsClientError() bool {
return o._statusCode/100 == 4
}
// IsServerError returns true when this delete github endpoint default response has a 5xx status code
func (o *DeleteGithubEndpointDefault) IsServerError() bool {
return o._statusCode/100 == 5
}
// IsCode returns true when this delete github endpoint default response a status code equal to that given
func (o *DeleteGithubEndpointDefault) IsCode(code int) bool {
return o._statusCode == code
}
// Code gets the status code for the delete github endpoint default response
func (o *DeleteGithubEndpointDefault) Code() int {
return o._statusCode
}
func (o *DeleteGithubEndpointDefault) Error() string {
return fmt.Sprintf("[DELETE /github/endpoints/{name}][%d] DeleteGithubEndpoint default %+v", o._statusCode, o.Payload)
}
func (o *DeleteGithubEndpointDefault) String() string {
return fmt.Sprintf("[DELETE /github/endpoints/{name}][%d] DeleteGithubEndpoint default %+v", o._statusCode, o.Payload)
}
func (o *DeleteGithubEndpointDefault) GetPayload() apiserver_params.APIErrorResponse {
return o.Payload
}
func (o *DeleteGithubEndpointDefault) 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
}

View file

@ -0,0 +1,231 @@
// 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 (
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
)
// New creates a new endpoints API client.
func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService {
return &Client{transport: transport, formats: formats}
}
/*
Client for endpoints API
*/
type Client struct {
transport runtime.ClientTransport
formats strfmt.Registry
}
// ClientOption is the option for Client methods
type ClientOption func(*runtime.ClientOperation)
// ClientService is the interface for Client methods
type ClientService interface {
CreateGithubEndpoint(params *CreateGithubEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateGithubEndpointOK, error)
DeleteGithubEndpoint(params *DeleteGithubEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error
GetGithubEndpoint(params *GetGithubEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetGithubEndpointOK, error)
ListGithubEndpoints(params *ListGithubEndpointsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListGithubEndpointsOK, error)
UpdateGithubEndpoint(params *UpdateGithubEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateGithubEndpointOK, error)
SetTransport(transport runtime.ClientTransport)
}
/*
CreateGithubEndpoint creates a git hub endpoint
*/
func (a *Client) CreateGithubEndpoint(params *CreateGithubEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateGithubEndpointOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewCreateGithubEndpointParams()
}
op := &runtime.ClientOperation{
ID: "CreateGithubEndpoint",
Method: "POST",
PathPattern: "/github/endpoints",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &CreateGithubEndpointReader{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.(*CreateGithubEndpointOK)
if ok {
return success, nil
}
// unexpected success response
unexpectedSuccess := result.(*CreateGithubEndpointDefault)
return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code())
}
/*
DeleteGithubEndpoint deletes a git hub endpoint
*/
func (a *Client) DeleteGithubEndpoint(params *DeleteGithubEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error {
// TODO: Validate the params before sending
if params == nil {
params = NewDeleteGithubEndpointParams()
}
op := &runtime.ClientOperation{
ID: "DeleteGithubEndpoint",
Method: "DELETE",
PathPattern: "/github/endpoints/{name}",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &DeleteGithubEndpointReader{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
}
/*
GetGithubEndpoint gets a git hub endpoint
*/
func (a *Client) GetGithubEndpoint(params *GetGithubEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetGithubEndpointOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewGetGithubEndpointParams()
}
op := &runtime.ClientOperation{
ID: "GetGithubEndpoint",
Method: "GET",
PathPattern: "/github/endpoints/{name}",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &GetGithubEndpointReader{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.(*GetGithubEndpointOK)
if ok {
return success, nil
}
// unexpected success response
unexpectedSuccess := result.(*GetGithubEndpointDefault)
return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code())
}
/*
ListGithubEndpoints lists all git hub endpoints
*/
func (a *Client) ListGithubEndpoints(params *ListGithubEndpointsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListGithubEndpointsOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewListGithubEndpointsParams()
}
op := &runtime.ClientOperation{
ID: "ListGithubEndpoints",
Method: "GET",
PathPattern: "/github/endpoints",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &ListGithubEndpointsReader{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.(*ListGithubEndpointsOK)
if ok {
return success, nil
}
// unexpected success response
unexpectedSuccess := result.(*ListGithubEndpointsDefault)
return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code())
}
/*
UpdateGithubEndpoint updates a git hub endpoint
*/
func (a *Client) UpdateGithubEndpoint(params *UpdateGithubEndpointParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateGithubEndpointOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewUpdateGithubEndpointParams()
}
op := &runtime.ClientOperation{
ID: "UpdateGithubEndpoint",
Method: "PUT",
PathPattern: "/github/endpoints/{name}",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &UpdateGithubEndpointReader{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.(*UpdateGithubEndpointOK)
if ok {
return success, nil
}
// unexpected success response
unexpectedSuccess := result.(*UpdateGithubEndpointDefault)
return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code())
}
// SetTransport changes the transport on the client
func (a *Client) SetTransport(transport runtime.ClientTransport) {
a.transport = transport
}

View file

@ -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"
)
// NewGetGithubEndpointParams creates a new GetGithubEndpointParams 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 NewGetGithubEndpointParams() *GetGithubEndpointParams {
return &GetGithubEndpointParams{
timeout: cr.DefaultTimeout,
}
}
// NewGetGithubEndpointParamsWithTimeout creates a new GetGithubEndpointParams object
// with the ability to set a timeout on a request.
func NewGetGithubEndpointParamsWithTimeout(timeout time.Duration) *GetGithubEndpointParams {
return &GetGithubEndpointParams{
timeout: timeout,
}
}
// NewGetGithubEndpointParamsWithContext creates a new GetGithubEndpointParams object
// with the ability to set a context for a request.
func NewGetGithubEndpointParamsWithContext(ctx context.Context) *GetGithubEndpointParams {
return &GetGithubEndpointParams{
Context: ctx,
}
}
// NewGetGithubEndpointParamsWithHTTPClient creates a new GetGithubEndpointParams object
// with the ability to set a custom HTTPClient for a request.
func NewGetGithubEndpointParamsWithHTTPClient(client *http.Client) *GetGithubEndpointParams {
return &GetGithubEndpointParams{
HTTPClient: client,
}
}
/*
GetGithubEndpointParams contains all the parameters to send to the API endpoint
for the get github endpoint operation.
Typically these are written to a http.Request.
*/
type GetGithubEndpointParams struct {
/* Name.
The name of the GitHub endpoint.
*/
Name string
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the get github endpoint params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *GetGithubEndpointParams) WithDefaults() *GetGithubEndpointParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the get github endpoint params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *GetGithubEndpointParams) SetDefaults() {
// no default values defined for this parameter
}
// WithTimeout adds the timeout to the get github endpoint params
func (o *GetGithubEndpointParams) WithTimeout(timeout time.Duration) *GetGithubEndpointParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the get github endpoint params
func (o *GetGithubEndpointParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the get github endpoint params
func (o *GetGithubEndpointParams) WithContext(ctx context.Context) *GetGithubEndpointParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the get github endpoint params
func (o *GetGithubEndpointParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the get github endpoint params
func (o *GetGithubEndpointParams) WithHTTPClient(client *http.Client) *GetGithubEndpointParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the get github endpoint params
func (o *GetGithubEndpointParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithName adds the name to the get github endpoint params
func (o *GetGithubEndpointParams) WithName(name string) *GetGithubEndpointParams {
o.SetName(name)
return o
}
// SetName adds the name to the get github endpoint params
func (o *GetGithubEndpointParams) SetName(name string) {
o.Name = name
}
// WriteToRequest writes these params to a swagger request
func (o *GetGithubEndpointParams) 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
}

View file

@ -0,0 +1,179 @@
// 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 (
"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"
)
// GetGithubEndpointReader is a Reader for the GetGithubEndpoint structure.
type GetGithubEndpointReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *GetGithubEndpointReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewGetGithubEndpointOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
default:
result := NewGetGithubEndpointDefault(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
}
}
// NewGetGithubEndpointOK creates a GetGithubEndpointOK with default headers values
func NewGetGithubEndpointOK() *GetGithubEndpointOK {
return &GetGithubEndpointOK{}
}
/*
GetGithubEndpointOK describes a response with status code 200, with default header values.
GithubEndpoint
*/
type GetGithubEndpointOK struct {
Payload garm_params.GithubEndpoint
}
// IsSuccess returns true when this get github endpoint o k response has a 2xx status code
func (o *GetGithubEndpointOK) IsSuccess() bool {
return true
}
// IsRedirect returns true when this get github endpoint o k response has a 3xx status code
func (o *GetGithubEndpointOK) IsRedirect() bool {
return false
}
// IsClientError returns true when this get github endpoint o k response has a 4xx status code
func (o *GetGithubEndpointOK) IsClientError() bool {
return false
}
// IsServerError returns true when this get github endpoint o k response has a 5xx status code
func (o *GetGithubEndpointOK) IsServerError() bool {
return false
}
// IsCode returns true when this get github endpoint o k response a status code equal to that given
func (o *GetGithubEndpointOK) IsCode(code int) bool {
return code == 200
}
// Code gets the status code for the get github endpoint o k response
func (o *GetGithubEndpointOK) Code() int {
return 200
}
func (o *GetGithubEndpointOK) Error() string {
return fmt.Sprintf("[GET /github/endpoints/{name}][%d] getGithubEndpointOK %+v", 200, o.Payload)
}
func (o *GetGithubEndpointOK) String() string {
return fmt.Sprintf("[GET /github/endpoints/{name}][%d] getGithubEndpointOK %+v", 200, o.Payload)
}
func (o *GetGithubEndpointOK) GetPayload() garm_params.GithubEndpoint {
return o.Payload
}
func (o *GetGithubEndpointOK) 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
}
// NewGetGithubEndpointDefault creates a GetGithubEndpointDefault with default headers values
func NewGetGithubEndpointDefault(code int) *GetGithubEndpointDefault {
return &GetGithubEndpointDefault{
_statusCode: code,
}
}
/*
GetGithubEndpointDefault describes a response with status code -1, with default header values.
APIErrorResponse
*/
type GetGithubEndpointDefault struct {
_statusCode int
Payload apiserver_params.APIErrorResponse
}
// IsSuccess returns true when this get github endpoint default response has a 2xx status code
func (o *GetGithubEndpointDefault) IsSuccess() bool {
return o._statusCode/100 == 2
}
// IsRedirect returns true when this get github endpoint default response has a 3xx status code
func (o *GetGithubEndpointDefault) IsRedirect() bool {
return o._statusCode/100 == 3
}
// IsClientError returns true when this get github endpoint default response has a 4xx status code
func (o *GetGithubEndpointDefault) IsClientError() bool {
return o._statusCode/100 == 4
}
// IsServerError returns true when this get github endpoint default response has a 5xx status code
func (o *GetGithubEndpointDefault) IsServerError() bool {
return o._statusCode/100 == 5
}
// IsCode returns true when this get github endpoint default response a status code equal to that given
func (o *GetGithubEndpointDefault) IsCode(code int) bool {
return o._statusCode == code
}
// Code gets the status code for the get github endpoint default response
func (o *GetGithubEndpointDefault) Code() int {
return o._statusCode
}
func (o *GetGithubEndpointDefault) Error() string {
return fmt.Sprintf("[GET /github/endpoints/{name}][%d] GetGithubEndpoint default %+v", o._statusCode, o.Payload)
}
func (o *GetGithubEndpointDefault) String() string {
return fmt.Sprintf("[GET /github/endpoints/{name}][%d] GetGithubEndpoint default %+v", o._statusCode, o.Payload)
}
func (o *GetGithubEndpointDefault) GetPayload() apiserver_params.APIErrorResponse {
return o.Payload
}
func (o *GetGithubEndpointDefault) 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
}

View file

@ -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"
)
// NewListGithubEndpointsParams creates a new ListGithubEndpointsParams 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 NewListGithubEndpointsParams() *ListGithubEndpointsParams {
return &ListGithubEndpointsParams{
timeout: cr.DefaultTimeout,
}
}
// NewListGithubEndpointsParamsWithTimeout creates a new ListGithubEndpointsParams object
// with the ability to set a timeout on a request.
func NewListGithubEndpointsParamsWithTimeout(timeout time.Duration) *ListGithubEndpointsParams {
return &ListGithubEndpointsParams{
timeout: timeout,
}
}
// NewListGithubEndpointsParamsWithContext creates a new ListGithubEndpointsParams object
// with the ability to set a context for a request.
func NewListGithubEndpointsParamsWithContext(ctx context.Context) *ListGithubEndpointsParams {
return &ListGithubEndpointsParams{
Context: ctx,
}
}
// NewListGithubEndpointsParamsWithHTTPClient creates a new ListGithubEndpointsParams object
// with the ability to set a custom HTTPClient for a request.
func NewListGithubEndpointsParamsWithHTTPClient(client *http.Client) *ListGithubEndpointsParams {
return &ListGithubEndpointsParams{
HTTPClient: client,
}
}
/*
ListGithubEndpointsParams contains all the parameters to send to the API endpoint
for the list github endpoints operation.
Typically these are written to a http.Request.
*/
type ListGithubEndpointsParams struct {
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the list github endpoints params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *ListGithubEndpointsParams) WithDefaults() *ListGithubEndpointsParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the list github endpoints params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *ListGithubEndpointsParams) SetDefaults() {
// no default values defined for this parameter
}
// WithTimeout adds the timeout to the list github endpoints params
func (o *ListGithubEndpointsParams) WithTimeout(timeout time.Duration) *ListGithubEndpointsParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the list github endpoints params
func (o *ListGithubEndpointsParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the list github endpoints params
func (o *ListGithubEndpointsParams) WithContext(ctx context.Context) *ListGithubEndpointsParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the list github endpoints params
func (o *ListGithubEndpointsParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the list github endpoints params
func (o *ListGithubEndpointsParams) WithHTTPClient(client *http.Client) *ListGithubEndpointsParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the list github endpoints params
func (o *ListGithubEndpointsParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WriteToRequest writes these params to a swagger request
func (o *ListGithubEndpointsParams) 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
}

View file

@ -0,0 +1,179 @@
// 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 (
"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"
)
// ListGithubEndpointsReader is a Reader for the ListGithubEndpoints structure.
type ListGithubEndpointsReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *ListGithubEndpointsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewListGithubEndpointsOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
default:
result := NewListGithubEndpointsDefault(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
}
}
// NewListGithubEndpointsOK creates a ListGithubEndpointsOK with default headers values
func NewListGithubEndpointsOK() *ListGithubEndpointsOK {
return &ListGithubEndpointsOK{}
}
/*
ListGithubEndpointsOK describes a response with status code 200, with default header values.
GithubEndpoints
*/
type ListGithubEndpointsOK struct {
Payload garm_params.GithubEndpoints
}
// IsSuccess returns true when this list github endpoints o k response has a 2xx status code
func (o *ListGithubEndpointsOK) IsSuccess() bool {
return true
}
// IsRedirect returns true when this list github endpoints o k response has a 3xx status code
func (o *ListGithubEndpointsOK) IsRedirect() bool {
return false
}
// IsClientError returns true when this list github endpoints o k response has a 4xx status code
func (o *ListGithubEndpointsOK) IsClientError() bool {
return false
}
// IsServerError returns true when this list github endpoints o k response has a 5xx status code
func (o *ListGithubEndpointsOK) IsServerError() bool {
return false
}
// IsCode returns true when this list github endpoints o k response a status code equal to that given
func (o *ListGithubEndpointsOK) IsCode(code int) bool {
return code == 200
}
// Code gets the status code for the list github endpoints o k response
func (o *ListGithubEndpointsOK) Code() int {
return 200
}
func (o *ListGithubEndpointsOK) Error() string {
return fmt.Sprintf("[GET /github/endpoints][%d] listGithubEndpointsOK %+v", 200, o.Payload)
}
func (o *ListGithubEndpointsOK) String() string {
return fmt.Sprintf("[GET /github/endpoints][%d] listGithubEndpointsOK %+v", 200, o.Payload)
}
func (o *ListGithubEndpointsOK) GetPayload() garm_params.GithubEndpoints {
return o.Payload
}
func (o *ListGithubEndpointsOK) 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
}
// NewListGithubEndpointsDefault creates a ListGithubEndpointsDefault with default headers values
func NewListGithubEndpointsDefault(code int) *ListGithubEndpointsDefault {
return &ListGithubEndpointsDefault{
_statusCode: code,
}
}
/*
ListGithubEndpointsDefault describes a response with status code -1, with default header values.
APIErrorResponse
*/
type ListGithubEndpointsDefault struct {
_statusCode int
Payload apiserver_params.APIErrorResponse
}
// IsSuccess returns true when this list github endpoints default response has a 2xx status code
func (o *ListGithubEndpointsDefault) IsSuccess() bool {
return o._statusCode/100 == 2
}
// IsRedirect returns true when this list github endpoints default response has a 3xx status code
func (o *ListGithubEndpointsDefault) IsRedirect() bool {
return o._statusCode/100 == 3
}
// IsClientError returns true when this list github endpoints default response has a 4xx status code
func (o *ListGithubEndpointsDefault) IsClientError() bool {
return o._statusCode/100 == 4
}
// IsServerError returns true when this list github endpoints default response has a 5xx status code
func (o *ListGithubEndpointsDefault) IsServerError() bool {
return o._statusCode/100 == 5
}
// IsCode returns true when this list github endpoints default response a status code equal to that given
func (o *ListGithubEndpointsDefault) IsCode(code int) bool {
return o._statusCode == code
}
// Code gets the status code for the list github endpoints default response
func (o *ListGithubEndpointsDefault) Code() int {
return o._statusCode
}
func (o *ListGithubEndpointsDefault) Error() string {
return fmt.Sprintf("[GET /github/endpoints][%d] ListGithubEndpoints default %+v", o._statusCode, o.Payload)
}
func (o *ListGithubEndpointsDefault) String() string {
return fmt.Sprintf("[GET /github/endpoints][%d] ListGithubEndpoints default %+v", o._statusCode, o.Payload)
}
func (o *ListGithubEndpointsDefault) GetPayload() apiserver_params.APIErrorResponse {
return o.Payload
}
func (o *ListGithubEndpointsDefault) 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
}

View file

@ -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"
)
// NewUpdateGithubEndpointParams creates a new UpdateGithubEndpointParams 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 NewUpdateGithubEndpointParams() *UpdateGithubEndpointParams {
return &UpdateGithubEndpointParams{
timeout: cr.DefaultTimeout,
}
}
// NewUpdateGithubEndpointParamsWithTimeout creates a new UpdateGithubEndpointParams object
// with the ability to set a timeout on a request.
func NewUpdateGithubEndpointParamsWithTimeout(timeout time.Duration) *UpdateGithubEndpointParams {
return &UpdateGithubEndpointParams{
timeout: timeout,
}
}
// NewUpdateGithubEndpointParamsWithContext creates a new UpdateGithubEndpointParams object
// with the ability to set a context for a request.
func NewUpdateGithubEndpointParamsWithContext(ctx context.Context) *UpdateGithubEndpointParams {
return &UpdateGithubEndpointParams{
Context: ctx,
}
}
// NewUpdateGithubEndpointParamsWithHTTPClient creates a new UpdateGithubEndpointParams object
// with the ability to set a custom HTTPClient for a request.
func NewUpdateGithubEndpointParamsWithHTTPClient(client *http.Client) *UpdateGithubEndpointParams {
return &UpdateGithubEndpointParams{
HTTPClient: client,
}
}
/*
UpdateGithubEndpointParams contains all the parameters to send to the API endpoint
for the update github endpoint operation.
Typically these are written to a http.Request.
*/
type UpdateGithubEndpointParams struct {
/* Body.
Parameters used when updating a GitHub endpoint.
*/
Body garm_params.UpdateGithubEndpointParams
/* Name.
The name of the GitHub endpoint.
*/
Name string
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the update github endpoint params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *UpdateGithubEndpointParams) WithDefaults() *UpdateGithubEndpointParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the update github endpoint params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *UpdateGithubEndpointParams) SetDefaults() {
// no default values defined for this parameter
}
// WithTimeout adds the timeout to the update github endpoint params
func (o *UpdateGithubEndpointParams) WithTimeout(timeout time.Duration) *UpdateGithubEndpointParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the update github endpoint params
func (o *UpdateGithubEndpointParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the update github endpoint params
func (o *UpdateGithubEndpointParams) WithContext(ctx context.Context) *UpdateGithubEndpointParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the update github endpoint params
func (o *UpdateGithubEndpointParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the update github endpoint params
func (o *UpdateGithubEndpointParams) WithHTTPClient(client *http.Client) *UpdateGithubEndpointParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the update github endpoint params
func (o *UpdateGithubEndpointParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithBody adds the body to the update github endpoint params
func (o *UpdateGithubEndpointParams) WithBody(body garm_params.UpdateGithubEndpointParams) *UpdateGithubEndpointParams {
o.SetBody(body)
return o
}
// SetBody adds the body to the update github endpoint params
func (o *UpdateGithubEndpointParams) SetBody(body garm_params.UpdateGithubEndpointParams) {
o.Body = body
}
// WithName adds the name to the update github endpoint params
func (o *UpdateGithubEndpointParams) WithName(name string) *UpdateGithubEndpointParams {
o.SetName(name)
return o
}
// SetName adds the name to the update github endpoint params
func (o *UpdateGithubEndpointParams) SetName(name string) {
o.Name = name
}
// WriteToRequest writes these params to a swagger request
func (o *UpdateGithubEndpointParams) 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
}

View file

@ -0,0 +1,179 @@
// 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 (
"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"
)
// UpdateGithubEndpointReader is a Reader for the UpdateGithubEndpoint structure.
type UpdateGithubEndpointReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *UpdateGithubEndpointReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewUpdateGithubEndpointOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
default:
result := NewUpdateGithubEndpointDefault(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
}
}
// NewUpdateGithubEndpointOK creates a UpdateGithubEndpointOK with default headers values
func NewUpdateGithubEndpointOK() *UpdateGithubEndpointOK {
return &UpdateGithubEndpointOK{}
}
/*
UpdateGithubEndpointOK describes a response with status code 200, with default header values.
GithubEndpoint
*/
type UpdateGithubEndpointOK struct {
Payload garm_params.GithubEndpoint
}
// IsSuccess returns true when this update github endpoint o k response has a 2xx status code
func (o *UpdateGithubEndpointOK) IsSuccess() bool {
return true
}
// IsRedirect returns true when this update github endpoint o k response has a 3xx status code
func (o *UpdateGithubEndpointOK) IsRedirect() bool {
return false
}
// IsClientError returns true when this update github endpoint o k response has a 4xx status code
func (o *UpdateGithubEndpointOK) IsClientError() bool {
return false
}
// IsServerError returns true when this update github endpoint o k response has a 5xx status code
func (o *UpdateGithubEndpointOK) IsServerError() bool {
return false
}
// IsCode returns true when this update github endpoint o k response a status code equal to that given
func (o *UpdateGithubEndpointOK) IsCode(code int) bool {
return code == 200
}
// Code gets the status code for the update github endpoint o k response
func (o *UpdateGithubEndpointOK) Code() int {
return 200
}
func (o *UpdateGithubEndpointOK) Error() string {
return fmt.Sprintf("[PUT /github/endpoints/{name}][%d] updateGithubEndpointOK %+v", 200, o.Payload)
}
func (o *UpdateGithubEndpointOK) String() string {
return fmt.Sprintf("[PUT /github/endpoints/{name}][%d] updateGithubEndpointOK %+v", 200, o.Payload)
}
func (o *UpdateGithubEndpointOK) GetPayload() garm_params.GithubEndpoint {
return o.Payload
}
func (o *UpdateGithubEndpointOK) 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
}
// NewUpdateGithubEndpointDefault creates a UpdateGithubEndpointDefault with default headers values
func NewUpdateGithubEndpointDefault(code int) *UpdateGithubEndpointDefault {
return &UpdateGithubEndpointDefault{
_statusCode: code,
}
}
/*
UpdateGithubEndpointDefault describes a response with status code -1, with default header values.
APIErrorResponse
*/
type UpdateGithubEndpointDefault struct {
_statusCode int
Payload apiserver_params.APIErrorResponse
}
// IsSuccess returns true when this update github endpoint default response has a 2xx status code
func (o *UpdateGithubEndpointDefault) IsSuccess() bool {
return o._statusCode/100 == 2
}
// IsRedirect returns true when this update github endpoint default response has a 3xx status code
func (o *UpdateGithubEndpointDefault) IsRedirect() bool {
return o._statusCode/100 == 3
}
// IsClientError returns true when this update github endpoint default response has a 4xx status code
func (o *UpdateGithubEndpointDefault) IsClientError() bool {
return o._statusCode/100 == 4
}
// IsServerError returns true when this update github endpoint default response has a 5xx status code
func (o *UpdateGithubEndpointDefault) IsServerError() bool {
return o._statusCode/100 == 5
}
// IsCode returns true when this update github endpoint default response a status code equal to that given
func (o *UpdateGithubEndpointDefault) IsCode(code int) bool {
return o._statusCode == code
}
// Code gets the status code for the update github endpoint default response
func (o *UpdateGithubEndpointDefault) Code() int {
return o._statusCode
}
func (o *UpdateGithubEndpointDefault) Error() string {
return fmt.Sprintf("[PUT /github/endpoints/{name}][%d] UpdateGithubEndpoint default %+v", o._statusCode, o.Payload)
}
func (o *UpdateGithubEndpointDefault) String() string {
return fmt.Sprintf("[PUT /github/endpoints/{name}][%d] UpdateGithubEndpoint default %+v", o._statusCode, o.Payload)
}
func (o *UpdateGithubEndpointDefault) GetPayload() apiserver_params.APIErrorResponse {
return o.Payload
}
func (o *UpdateGithubEndpointDefault) 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
}

View file

@ -12,6 +12,7 @@ import (
"github.com/cloudbase/garm/client/controller_info"
"github.com/cloudbase/garm/client/credentials"
"github.com/cloudbase/garm/client/endpoints"
"github.com/cloudbase/garm/client/enterprises"
"github.com/cloudbase/garm/client/first_run"
"github.com/cloudbase/garm/client/instances"
@ -68,6 +69,7 @@ func New(transport runtime.ClientTransport, formats strfmt.Registry) *GarmAPI {
cli.Transport = transport
cli.ControllerInfo = controller_info.New(transport, formats)
cli.Credentials = credentials.New(transport, formats)
cli.Endpoints = endpoints.New(transport, formats)
cli.Enterprises = enterprises.New(transport, formats)
cli.FirstRun = first_run.New(transport, formats)
cli.Instances = instances.New(transport, formats)
@ -126,6 +128,8 @@ type GarmAPI struct {
Credentials credentials.ClientService
Endpoints endpoints.ClientService
Enterprises enterprises.ClientService
FirstRun first_run.ClientService
@ -154,6 +158,7 @@ func (c *GarmAPI) SetTransport(transport runtime.ClientTransport) {
c.Transport = transport
c.ControllerInfo.SetTransport(transport)
c.Credentials.SetTransport(transport)
c.Endpoints.SetTransport(transport)
c.Enterprises.SetTransport(transport)
c.FirstRun.SetTransport(transport)
c.Instances.SetTransport(transport)

View file

@ -0,0 +1,30 @@
package cmd
import "github.com/spf13/cobra"
var (
endpointName string
endpointBaseURL string
endpointUploadURL string
endpointAPIBaseURL string
endpointCACertPath string
endpointDescription string
)
// githubCmd represents the the github command. This command has a set
// of subcommands that allow configuring and managing GitHub endpoints
// and credentials.
var githubCmd = &cobra.Command{
Use: "github",
Aliases: []string{"gh"},
SilenceUsage: true,
Short: "Manage GitHub resources",
Long: `Manage GitHub related resources.
This command allows you to configure and manage GitHub endpoints and credentials`,
Run: nil,
}
func init() {
rootCmd.AddCommand(githubCmd)
}

View file

@ -0,0 +1,277 @@
package cmd
import (
"crypto/x509"
"encoding/pem"
"fmt"
"os"
"github.com/jedib0t/go-pretty/v6/table"
"github.com/spf13/cobra"
apiClientEndpoints "github.com/cloudbase/garm/client/endpoints"
"github.com/cloudbase/garm/params"
)
var githubEndpointCmd = &cobra.Command{
Use: "endpoint",
SilenceUsage: true,
Short: "Manage GitHub endpoints",
Long: `Manage GitHub endpoints.
This command allows you to configure and manage GitHub endpoints`,
Run: nil,
}
var githubEndpointListCmd = &cobra.Command{
Use: "list",
Aliases: []string{"ls"},
SilenceUsage: true,
Short: "List GitHub endpoints",
Long: `List all configured GitHub endpoints.`,
RunE: func(_ *cobra.Command, _ []string) error {
if needsInit {
return errNeedsInitError
}
newGHListReq := apiClientEndpoints.NewListGithubEndpointsParams()
response, err := apiCli.Endpoints.ListGithubEndpoints(newGHListReq, authToken)
if err != nil {
return err
}
formatEndpoints(response.Payload)
return nil
},
}
var githubEndpointShowCmd = &cobra.Command{
Use: "show",
Aliases: []string{"get"},
SilenceUsage: true,
Short: "Show GitHub endpoint",
Long: `Show details of a GitHub 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")
}
newGHShowReq := apiClientEndpoints.NewGetGithubEndpointParams()
newGHShowReq.Name = args[0]
response, err := apiCli.Endpoints.GetGithubEndpoint(newGHShowReq, authToken)
if err != nil {
return err
}
formatOneEndpoint(response.Payload)
return nil
},
}
var githubEndpointCreateCmd = &cobra.Command{
Use: "create",
SilenceUsage: true,
Short: "Create GitHub endpoint",
Long: `Create a new GitHub endpoint.`,
RunE: func(_ *cobra.Command, _ []string) error {
if needsInit {
return errNeedsInitError
}
createParams, err := parseCreateParams()
if err != nil {
return err
}
newGHCreateReq := apiClientEndpoints.NewCreateGithubEndpointParams()
newGHCreateReq.Body = createParams
response, err := apiCli.Endpoints.CreateGithubEndpoint(newGHCreateReq, authToken)
if err != nil {
return err
}
formatOneEndpoint(response.Payload)
return nil
},
}
var githubEndpointDeleteCmd = &cobra.Command{
Use: "delete",
Aliases: []string{"remove", "rm"},
SilenceUsage: true,
Short: "Delete GitHub endpoint",
Long: "Delete a GitHub 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")
}
newGHDeleteReq := apiClientEndpoints.NewDeleteGithubEndpointParams()
newGHDeleteReq.Name = args[0]
if err := apiCli.Endpoints.DeleteGithubEndpoint(newGHDeleteReq, authToken); err != nil {
return err
}
return nil
},
}
var githubEndpointUpdateCmd = &cobra.Command{
Use: "update",
Short: "Update GitHub endpoint",
Long: "Update a GitHub 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.UpdateGithubEndpointParams{}
if cmd.Flags().Changed("ca-cert-path") {
cert, err := parseReadAndParsCABundle()
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("upload-url") {
updateParams.UploadBaseURL = &endpointUploadURL
}
if cmd.Flags().Changed("api-base-url") {
updateParams.APIBaseURL = &endpointAPIBaseURL
}
newGHEndpointUpdateReq := apiClientEndpoints.NewUpdateGithubEndpointParams()
newGHEndpointUpdateReq.Name = args[0]
newGHEndpointUpdateReq.Body = updateParams
response, err := apiCli.Endpoints.UpdateGithubEndpoint(newGHEndpointUpdateReq, authToken)
if err != nil {
return err
}
formatOneEndpoint(response.Payload)
return nil
},
}
func init() {
githubEndpointCreateCmd.Flags().StringVar(&endpointName, "name", "", "Name of the GitHub endpoint")
githubEndpointCreateCmd.Flags().StringVar(&endpointDescription, "description", "", "Description for the github endpoint")
githubEndpointCreateCmd.Flags().StringVar(&endpointBaseURL, "base-url", "", "Base URL of the GitHub endpoint")
githubEndpointCreateCmd.Flags().StringVar(&endpointUploadURL, "upload-url", "", "Upload URL of the GitHub endpoint")
githubEndpointCreateCmd.Flags().StringVar(&endpointAPIBaseURL, "api-base-url", "", "API Base URL of the GitHub endpoint")
githubEndpointCreateCmd.Flags().StringVar(&endpointCACertPath, "ca-cert-path", "", "CA Cert Path of the GitHub endpoint")
githubEndpointCreateCmd.MarkFlagRequired("name")
githubEndpointCreateCmd.MarkFlagRequired("base-url")
githubEndpointCreateCmd.MarkFlagRequired("api-base-url")
githubEndpointCreateCmd.MarkFlagRequired("upload-url")
githubEndpointUpdateCmd.Flags().StringVar(&endpointDescription, "description", "", "Description for the github endpoint")
githubEndpointUpdateCmd.Flags().StringVar(&endpointBaseURL, "base-url", "", "Base URL of the GitHub endpoint")
githubEndpointUpdateCmd.Flags().StringVar(&endpointUploadURL, "upload-url", "", "Upload URL of the GitHub endpoint")
githubEndpointUpdateCmd.Flags().StringVar(&endpointAPIBaseURL, "api-base-url", "", "API Base URL of the GitHub endpoint")
githubEndpointUpdateCmd.Flags().StringVar(&endpointCACertPath, "ca-cert-path", "", "CA Cert Path of the GitHub endpoint")
githubEndpointCmd.AddCommand(githubEndpointListCmd)
githubEndpointCmd.AddCommand(githubEndpointShowCmd)
githubEndpointCmd.AddCommand(githubEndpointCreateCmd)
githubEndpointCmd.AddCommand(githubEndpointDeleteCmd)
githubEndpointCmd.AddCommand(githubEndpointUpdateCmd)
githubCmd.AddCommand(githubEndpointCmd)
}
func parseReadAndParsCABundle() ([]byte, error) {
if endpointCACertPath == "" {
return nil, nil
}
if _, err := os.Stat(endpointCACertPath); os.IsNotExist(err) {
return nil, fmt.Errorf("CA cert file not found: %s", endpointCACertPath)
}
contents, err := os.ReadFile(endpointCACertPath)
if err != nil {
return nil, err
}
pemBlock, _ := pem.Decode(contents)
if pemBlock == nil {
return nil, fmt.Errorf("failed to decode PEM block")
}
if _, err := x509.ParseCertificates(pemBlock.Bytes); err != nil {
return nil, fmt.Errorf("failed to parse CA cert bundle: %w", err)
}
return contents, nil
}
func parseCreateParams() (params.CreateGithubEndpointParams, error) {
certBundleBytes, err := parseReadAndParsCABundle()
if err != nil {
return params.CreateGithubEndpointParams{}, err
}
ret := params.CreateGithubEndpointParams{
Name: endpointName,
BaseURL: endpointBaseURL,
UploadBaseURL: endpointUploadURL,
APIBaseURL: endpointAPIBaseURL,
Description: endpointDescription,
CACertBundle: certBundleBytes,
}
return ret, nil
}
func formatEndpoints(endpoints params.GithubEndpoints) {
t := table.NewWriter()
header := table.Row{"Name", "Base URL", "Description"}
t.AppendHeader(header)
for _, val := range endpoints {
t.AppendRow([]interface{}{val.Name, val.BaseURL, val.Description})
t.AppendSeparator()
}
fmt.Println(t.Render())
}
func formatOneEndpoint(endpoint params.GithubEndpoint) {
t := table.NewWriter()
header := table.Row{"Field", "Value"}
t.AppendHeader(header)
t.AppendRow([]interface{}{"Name", endpoint.Name})
t.AppendRow([]interface{}{"Base URL", endpoint.BaseURL})
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)})
}
t.SetColumnConfigs([]table.ColumnConfig{
{Number: 1, AutoMerge: true},
{Number: 2, AutoMerge: false, WidthMax: 100},
})
fmt.Println(t.Render())
}

View file

@ -218,11 +218,11 @@ func (s *EnterpriseTestSuite) TestCreateEnterpriseDBCreateErr() {
s.Fixtures.SQLMock.
ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_credentials` WHERE name = ? AND `github_credentials`.`deleted_at` IS NULL ORDER BY `github_credentials`.`id` LIMIT 1")).
WithArgs(s.Fixtures.Enterprises[0].CredentialsName).
WillReturnRows(sqlmock.NewRows([]string{"id", "endpoint_name"}).AddRow(s.testCreds.ID, s.testCreds.Endpoint))
WillReturnRows(sqlmock.NewRows([]string{"id", "endpoint_name"}).AddRow(s.testCreds.ID, s.testCreds.Endpoint.Name))
s.Fixtures.SQLMock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_endpoints` WHERE `github_endpoints`.`name` = ? AND `github_endpoints`.`deleted_at` IS NULL")).
WithArgs(s.testCreds.Endpoint).
WithArgs(s.testCreds.Endpoint.Name).
WillReturnRows(sqlmock.NewRows([]string{"name"}).
AddRow(s.testCreds.Endpoint))
AddRow(s.testCreds.Endpoint.Name))
s.Fixtures.SQLMock.
ExpectExec(regexp.QuoteMeta("INSERT INTO `enterprises`")).
WillReturnError(fmt.Errorf("creating enterprise mock error"))
@ -356,11 +356,11 @@ func (s *EnterpriseTestSuite) TestUpdateEnterpriseDBEncryptErr() {
ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_credentials` WHERE name = ? AND `github_credentials`.`deleted_at` IS NULL ORDER BY `github_credentials`.`id` LIMIT ?")).
WithArgs(s.secondaryTestCreds.Name, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "endpoint_name"}).
AddRow(s.secondaryTestCreds.ID, s.secondaryTestCreds.Endpoint))
AddRow(s.secondaryTestCreds.ID, s.secondaryTestCreds.Endpoint.Name))
s.Fixtures.SQLMock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_endpoints` WHERE `github_endpoints`.`name` = ? AND `github_endpoints`.`deleted_at` IS NULL")).
WithArgs(s.testCreds.Endpoint).
WithArgs(s.testCreds.Endpoint.Name).
WillReturnRows(sqlmock.NewRows([]string{"name"}).
AddRow(s.secondaryTestCreds.Endpoint))
AddRow(s.secondaryTestCreds.Endpoint.Name))
s.Fixtures.SQLMock.ExpectRollback()
_, err := s.StoreSQLMocked.UpdateEnterprise(s.adminCtx, s.Fixtures.Enterprises[0].ID, s.Fixtures.UpdateRepoParams)
@ -381,11 +381,11 @@ func (s *EnterpriseTestSuite) TestUpdateEnterpriseDBSaveErr() {
ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_credentials` WHERE name = ? AND `github_credentials`.`deleted_at` IS NULL ORDER BY `github_credentials`.`id` LIMIT ?")).
WithArgs(s.secondaryTestCreds.Name, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "endpoint_name"}).
AddRow(s.secondaryTestCreds.ID, s.secondaryTestCreds.Endpoint))
AddRow(s.secondaryTestCreds.ID, s.secondaryTestCreds.Endpoint.Name))
s.Fixtures.SQLMock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_endpoints` WHERE `github_endpoints`.`name` = ? AND `github_endpoints`.`deleted_at` IS NULL")).
WithArgs(s.testCreds.Endpoint).
WithArgs(s.testCreds.Endpoint.Name).
WillReturnRows(sqlmock.NewRows([]string{"name"}).
AddRow(s.secondaryTestCreds.Endpoint))
AddRow(s.secondaryTestCreds.Endpoint.Name))
s.Fixtures.SQLMock.
ExpectExec(("UPDATE `enterprises` SET")).
WillReturnError(fmt.Errorf("saving enterprise mock error"))
@ -412,11 +412,11 @@ func (s *EnterpriseTestSuite) TestUpdateEnterpriseDBDecryptingErr() {
ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_credentials` WHERE name = ? AND `github_credentials`.`deleted_at` IS NULL ORDER BY `github_credentials`.`id` LIMIT ?")).
WithArgs(s.secondaryTestCreds.Name, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "endpoint_name"}).
AddRow(s.secondaryTestCreds.ID, s.secondaryTestCreds.Endpoint))
AddRow(s.secondaryTestCreds.ID, s.secondaryTestCreds.Endpoint.Name))
s.Fixtures.SQLMock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_endpoints` WHERE `github_endpoints`.`name` = ? AND `github_endpoints`.`deleted_at` IS NULL")).
WithArgs(s.testCreds.Endpoint).
WithArgs(s.testCreds.Endpoint.Name).
WillReturnRows(sqlmock.NewRows([]string{"name"}).
AddRow(s.secondaryTestCreds.Endpoint))
AddRow(s.secondaryTestCreds.Endpoint.Name))
s.Fixtures.SQLMock.ExpectRollback()
_, err := s.StoreSQLMocked.UpdateEnterprise(s.adminCtx, s.Fixtures.Enterprises[0].ID, s.Fixtures.UpdateRepoParams)

View file

@ -36,6 +36,11 @@ func (s *sqlDatabase) sqlToCommonGithubCredentials(creds GithubCredentials) (par
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,
@ -45,7 +50,7 @@ func (s *sqlDatabase) sqlToCommonGithubCredentials(creds GithubCredentials) (par
UploadBaseURL: creds.Endpoint.UploadBaseURL,
CABundle: creds.Endpoint.CACertBundle,
AuthType: creds.AuthType,
Endpoint: creds.Endpoint.Name,
Endpoint: ep,
CredentialsPayload: data,
}
@ -216,8 +221,29 @@ func (s *sqlDatabase) DeleteGithubEndpoint(_ context.Context, name string) error
}
}
if credsCount > 0 {
return errors.New("cannot delete endpoint with 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 github 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 github 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 github 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 {

View file

@ -222,7 +222,7 @@ func (s *OrgTestSuite) TestCreateOrganizationDBCreateErr() {
WillReturnRows(sqlmock.NewRows([]string{"id", "endpoint_name"}).
AddRow(s.testCreds.ID, s.githubEndpoint.Name))
s.Fixtures.SQLMock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_endpoints` WHERE `github_endpoints`.`name` = ? AND `github_endpoints`.`deleted_at` IS NULL")).
WithArgs(s.testCreds.Endpoint).
WithArgs(s.testCreds.Endpoint.Name).
WillReturnRows(sqlmock.NewRows([]string{"name"}).
AddRow(s.githubEndpoint.Name))
s.Fixtures.SQLMock.
@ -358,11 +358,11 @@ func (s *OrgTestSuite) TestUpdateOrganizationDBEncryptErr() {
ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_credentials` WHERE name = ? AND `github_credentials`.`deleted_at` IS NULL ORDER BY `github_credentials`.`id` LIMIT ?")).
WithArgs(s.secondaryTestCreds.Name, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "endpoint_name"}).
AddRow(s.secondaryTestCreds.ID, s.secondaryTestCreds.Endpoint))
AddRow(s.secondaryTestCreds.ID, s.secondaryTestCreds.Endpoint.Name))
s.Fixtures.SQLMock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_endpoints` WHERE `github_endpoints`.`name` = ? AND `github_endpoints`.`deleted_at` IS NULL")).
WithArgs(s.testCreds.Endpoint).
WithArgs(s.testCreds.Endpoint.Name).
WillReturnRows(sqlmock.NewRows([]string{"name"}).
AddRow(s.secondaryTestCreds.Endpoint))
AddRow(s.secondaryTestCreds.Endpoint.Name))
s.Fixtures.SQLMock.ExpectRollback()
_, err := s.StoreSQLMocked.UpdateOrganization(s.adminCtx, s.Fixtures.Orgs[0].ID, s.Fixtures.UpdateRepoParams)
@ -383,11 +383,11 @@ func (s *OrgTestSuite) TestUpdateOrganizationDBSaveErr() {
ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_credentials` WHERE name = ? AND `github_credentials`.`deleted_at` IS NULL ORDER BY `github_credentials`.`id` LIMIT ?")).
WithArgs(s.secondaryTestCreds.Name, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "endpoint_name"}).
AddRow(s.secondaryTestCreds.ID, s.secondaryTestCreds.Endpoint))
AddRow(s.secondaryTestCreds.ID, s.secondaryTestCreds.Endpoint.Name))
s.Fixtures.SQLMock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_endpoints` WHERE `github_endpoints`.`name` = ? AND `github_endpoints`.`deleted_at` IS NULL")).
WithArgs(s.testCreds.Endpoint).
WithArgs(s.testCreds.Endpoint.Name).
WillReturnRows(sqlmock.NewRows([]string{"name"}).
AddRow(s.secondaryTestCreds.Endpoint))
AddRow(s.secondaryTestCreds.Endpoint.Name))
s.Fixtures.SQLMock.
ExpectExec(("UPDATE `organizations` SET")).
WillReturnError(fmt.Errorf("saving org mock error"))
@ -414,11 +414,11 @@ func (s *OrgTestSuite) TestUpdateOrganizationDBDecryptingErr() {
ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_credentials` WHERE name = ? AND `github_credentials`.`deleted_at` IS NULL ORDER BY `github_credentials`.`id` LIMIT ?")).
WithArgs(s.secondaryTestCreds.Name, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "endpoint_name"}).
AddRow(s.secondaryTestCreds.ID, s.secondaryTestCreds.Endpoint))
AddRow(s.secondaryTestCreds.ID, s.secondaryTestCreds.Endpoint.Name))
s.Fixtures.SQLMock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_endpoints` WHERE `github_endpoints`.`name` = ? AND `github_endpoints`.`deleted_at` IS NULL")).
WithArgs(s.testCreds.Endpoint).
WithArgs(s.testCreds.Endpoint.Name).
WillReturnRows(sqlmock.NewRows([]string{"name"}).
AddRow(s.secondaryTestCreds.Endpoint))
AddRow(s.secondaryTestCreds.Endpoint.Name))
s.Fixtures.SQLMock.ExpectRollback()
_, err := s.StoreSQLMocked.UpdateOrganization(s.adminCtx, s.Fixtures.Orgs[0].ID, s.Fixtures.UpdateRepoParams)

View file

@ -238,7 +238,7 @@ func (s *RepoTestSuite) TestCreateRepositoryInvalidDBCreateErr() {
WillReturnRows(sqlmock.NewRows([]string{"id", "endpoint_name"}).
AddRow(s.testCreds.ID, s.githubEndpoint.Name))
s.Fixtures.SQLMock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_endpoints` WHERE `github_endpoints`.`name` = ? AND `github_endpoints`.`deleted_at` IS NULL")).
WithArgs(s.testCreds.Endpoint).
WithArgs(s.testCreds.Endpoint.Name).
WillReturnRows(sqlmock.NewRows([]string{"name"}).
AddRow(s.githubEndpoint.Name))
s.Fixtures.SQLMock.
@ -396,11 +396,11 @@ func (s *RepoTestSuite) TestUpdateRepositoryDBEncryptErr() {
ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_credentials` WHERE name = ? AND `github_credentials`.`deleted_at` IS NULL ORDER BY `github_credentials`.`id` LIMIT ?")).
WithArgs(s.secondaryTestCreds.Name, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "endpoint_name"}).
AddRow(s.secondaryTestCreds.ID, s.secondaryTestCreds.Endpoint))
AddRow(s.secondaryTestCreds.ID, s.secondaryTestCreds.Endpoint.Name))
s.Fixtures.SQLMock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_endpoints` WHERE `github_endpoints`.`name` = ? AND `github_endpoints`.`deleted_at` IS NULL")).
WithArgs(s.testCreds.Endpoint).
WithArgs(s.testCreds.Endpoint.Name).
WillReturnRows(sqlmock.NewRows([]string{"name"}).
AddRow(s.secondaryTestCreds.Endpoint))
AddRow(s.secondaryTestCreds.Endpoint.Name))
s.Fixtures.SQLMock.ExpectRollback()
_, err := s.StoreSQLMocked.UpdateRepository(s.adminCtx, s.Fixtures.Repos[0].ID, s.Fixtures.UpdateRepoParams)
@ -421,11 +421,11 @@ func (s *RepoTestSuite) TestUpdateRepositoryDBSaveErr() {
ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_credentials` WHERE name = ? AND `github_credentials`.`deleted_at` IS NULL ORDER BY `github_credentials`.`id` LIMIT ?")).
WithArgs(s.secondaryTestCreds.Name, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "endpoint_name"}).
AddRow(s.secondaryTestCreds.ID, s.secondaryTestCreds.Endpoint))
AddRow(s.secondaryTestCreds.ID, s.secondaryTestCreds.Endpoint.Name))
s.Fixtures.SQLMock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_endpoints` WHERE `github_endpoints`.`name` = ? AND `github_endpoints`.`deleted_at` IS NULL")).
WithArgs(s.testCreds.Endpoint).
WithArgs(s.testCreds.Endpoint.Name).
WillReturnRows(sqlmock.NewRows([]string{"name"}).
AddRow(s.secondaryTestCreds.Endpoint))
AddRow(s.secondaryTestCreds.Endpoint.Name))
s.Fixtures.SQLMock.
ExpectExec(("UPDATE `repositories` SET")).
WillReturnError(fmt.Errorf("saving repo mock error"))
@ -451,11 +451,11 @@ func (s *RepoTestSuite) TestUpdateRepositoryDBDecryptingErr() {
ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_credentials` WHERE name = ? AND `github_credentials`.`deleted_at` IS NULL ORDER BY `github_credentials`.`id` LIMIT ?")).
WithArgs(s.secondaryTestCreds.Name, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "endpoint_name"}).
AddRow(s.secondaryTestCreds.ID, s.secondaryTestCreds.Endpoint))
AddRow(s.secondaryTestCreds.ID, s.secondaryTestCreds.Endpoint.Name))
s.Fixtures.SQLMock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `github_endpoints` WHERE `github_endpoints`.`name` = ? AND `github_endpoints`.`deleted_at` IS NULL")).
WithArgs(s.testCreds.Endpoint).
WithArgs(s.testCreds.Endpoint.Name).
WillReturnRows(sqlmock.NewRows([]string{"name"}).
AddRow(s.secondaryTestCreds.Endpoint))
AddRow(s.secondaryTestCreds.Endpoint.Name))
s.Fixtures.SQLMock.ExpectRollback()
_, err := s.StoreSQLMocked.UpdateRepository(s.adminCtx, s.Fixtures.Repos[0].ID, s.Fixtures.UpdateRepoParams)

View file

@ -567,7 +567,7 @@ type GithubCredentials struct {
Repositories []Repository `json:"repositories,omitempty"`
Organizations []Organization `json:"organizations,omitempty"`
Enterprises []Enterprise `json:"enterprises,omitempty"`
Endpoint string `json:"endpoint"`
Endpoint GithubEndpoint `json:"endpoint"`
CredentialsPayload []byte `json:"-"`
}
@ -802,13 +802,16 @@ func (g GithubEntity) String() string {
return ""
}
// used by swagger client generated code
type GithubEndpoints []GithubEndpoint
type GithubEndpoint struct {
Name string `json:"name"`
Description string `json:"description"`
APIBaseURL string `json:"api_base_url"`
UploadBaseURL string `json:"upload_base_url"`
BaseURL string `json:"base_url"`
CACertBundle []byte `json:"ca_cert_bundle"`
CACertBundle []byte `json:"ca_cert_bundle,omitempty"`
Credentials []GithubCredentials `json:"credentials"`
Credentials []GithubCredentials `json:"credentials,omitempty"`
}

View file

@ -19,12 +19,17 @@ import (
"encoding/json"
"encoding/pem"
"fmt"
"net/url"
"github.com/cloudbase/garm-provider-common/errors"
commonParams "github.com/cloudbase/garm-provider-common/params"
)
const DefaultRunnerPrefix = "garm"
const (
DefaultRunnerPrefix string = "garm"
httpsScheme string = "https"
httpScheme string = "http"
)
type InstanceRequest struct {
Name string `json:"name"`
@ -269,20 +274,128 @@ type InstanceUpdateMessage struct {
}
type CreateGithubEndpointParams struct {
Name string `json:"name"`
Description string `json:"description"`
APIBaseURL string `json:"api_base_url"`
UploadBaseURL string `json:"upload_base_url"`
BaseURL string `json:"base_url"`
CACertBundle []byte `json:"ca_cert_bundle"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
APIBaseURL string `json:"api_base_url,omitempty"`
UploadBaseURL string `json:"upload_base_url,omitempty"`
BaseURL string `json:"base_url,omitempty"`
CACertBundle []byte `json:"ca_cert_bundle,omitempty"`
}
func (c CreateGithubEndpointParams) Validate() error {
if c.APIBaseURL == "" {
return errors.NewBadRequestError("missing api_base_url")
}
url, err := url.Parse(c.APIBaseURL)
if err != nil || url.Scheme == "" || url.Host == "" {
return errors.NewBadRequestError("invalid api_base_url")
}
switch url.Scheme {
case httpsScheme, httpScheme:
default:
return errors.NewBadRequestError("invalid api_base_url")
}
if c.UploadBaseURL == "" {
return errors.NewBadRequestError("missing upload_base_url")
}
url, err = url.Parse(c.UploadBaseURL)
if err != nil || url.Scheme == "" || url.Host == "" {
return errors.NewBadRequestError("invalid upload_base_url")
}
switch url.Scheme {
case httpsScheme, httpScheme:
default:
return errors.NewBadRequestError("invalid api_base_url")
}
if c.BaseURL == "" {
return errors.NewBadRequestError("missing base_url")
}
url, err = url.Parse(c.BaseURL)
if err != nil || url.Scheme == "" || url.Host == "" {
return errors.NewBadRequestError("invalid base_url")
}
switch url.Scheme {
case httpsScheme, httpScheme:
default:
return errors.NewBadRequestError("invalid api_base_url")
}
if c.CACertBundle != nil {
block, _ := pem.Decode(c.CACertBundle)
if block == nil {
return errors.NewBadRequestError("invalid ca_cert_bundle")
}
if _, err := x509.ParseCertificates(block.Bytes); err != nil {
return errors.NewBadRequestError("invalid ca_cert_bundle")
}
}
return nil
}
type UpdateGithubEndpointParams struct {
Description *string `json:"description"`
APIBaseURL *string `json:"api_base_url"`
UploadBaseURL *string `json:"upload_base_url"`
BaseURL *string `json:"base_url"`
CACertBundle []byte `json:"ca_cert_bundle"`
Description *string `json:"description,omitempty"`
APIBaseURL *string `json:"api_base_url,omitempty"`
UploadBaseURL *string `json:"upload_base_url,omitempty"`
BaseURL *string `json:"base_url,omitempty"`
CACertBundle []byte `json:"ca_cert_bundle,omitempty"`
}
func (u UpdateGithubEndpointParams) Validate() error {
if u.APIBaseURL != nil {
url, err := url.Parse(*u.APIBaseURL)
if err != nil || url.Scheme == "" || url.Host == "" {
return errors.NewBadRequestError("invalid api_base_url")
}
switch url.Scheme {
case httpsScheme, httpScheme:
default:
return errors.NewBadRequestError("invalid api_base_url")
}
}
if u.UploadBaseURL != nil {
url, err := url.Parse(*u.UploadBaseURL)
if err != nil || url.Scheme == "" || url.Host == "" {
return errors.NewBadRequestError("invalid upload_base_url")
}
switch url.Scheme {
case httpsScheme, httpScheme:
default:
return errors.NewBadRequestError("invalid api_base_url")
}
}
if u.BaseURL != nil {
url, err := url.Parse(*u.BaseURL)
if err != nil || url.Scheme == "" || url.Host == "" {
return errors.NewBadRequestError("invalid base_url")
}
switch url.Scheme {
case httpsScheme, httpScheme:
default:
return errors.NewBadRequestError("invalid api_base_url")
}
}
if u.CACertBundle != nil {
block, _ := pem.Decode(u.CACertBundle)
if block == nil {
return errors.NewBadRequestError("invalid ca_cert_bundle")
}
if _, err := x509.ParseCertificates(block.Bytes); err != nil {
return errors.NewBadRequestError("invalid ca_cert_bundle")
}
}
return nil
}
type GithubPAT struct {

82
runner/endpoints.go Normal file
View file

@ -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) CreateGithubEndpoint(ctx context.Context, param params.CreateGithubEndpointParams) (params.GithubEndpoint, error) {
if !auth.IsAdmin(ctx) {
return params.GithubEndpoint{}, runnerErrors.ErrUnauthorized
}
if err := param.Validate(); err != nil {
return params.GithubEndpoint{}, errors.Wrap(err, "failed to validate github endpoint params")
}
ep, err := r.store.CreateGithubEndpoint(ctx, param)
if err != nil {
return params.GithubEndpoint{}, errors.Wrap(err, "failed to create github endpoint")
}
return ep, nil
}
func (r *Runner) GetGithubEndpoint(ctx context.Context, name string) (params.GithubEndpoint, error) {
if !auth.IsAdmin(ctx) {
return params.GithubEndpoint{}, runnerErrors.ErrUnauthorized
}
endpoint, err := r.store.GetGithubEndpoint(ctx, name)
if err != nil {
return params.GithubEndpoint{}, errors.Wrap(err, "failed to get github endpoint")
}
return endpoint, nil
}
func (r *Runner) DeleteGithubEndpoint(ctx context.Context, name string) error {
if !auth.IsAdmin(ctx) {
return runnerErrors.ErrUnauthorized
}
err := r.store.DeleteGithubEndpoint(ctx, name)
if err != nil {
return errors.Wrap(err, "failed to delete github endpoint")
}
return nil
}
func (r *Runner) UpdateGithubEndpoint(ctx context.Context, name string, param params.UpdateGithubEndpointParams) (params.GithubEndpoint, error) {
if !auth.IsAdmin(ctx) {
return params.GithubEndpoint{}, runnerErrors.ErrUnauthorized
}
if err := param.Validate(); err != nil {
return params.GithubEndpoint{}, errors.Wrap(err, "failed to validate github endpoint params")
}
newEp, err := r.store.UpdateGithubEndpoint(ctx, name, param)
if err != nil {
return params.GithubEndpoint{}, errors.Wrap(err, "failed to update github endpoint")
}
return newEp, nil
}
func (r *Runner) ListGithubEndpoints(ctx context.Context) ([]params.GithubEndpoint, error) {
if !auth.IsAdmin(ctx) {
return nil, runnerErrors.ErrUnauthorized
}
endpoints, err := r.store.ListGithubEndpoints(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to list github endpoints")
}
return endpoints, nil
}