diff --git a/.github/workflows/build-and-push.yml b/.github/workflows/build-and-push.yml new file mode 100644 index 00000000..b6c37a71 --- /dev/null +++ b/.github/workflows/build-and-push.yml @@ -0,0 +1,49 @@ +name: "Build GARM images" +on: + workflow_dispatch: + inputs: + push_to_project: + description: "Project to build images for" + required: true + default: "ghcr.io/cloudbase" + ref: + description: "Ref to build" + required: true + default: "main" + +permissions: + contents: read + +jobs: + images: + permissions: + packages: write + name: "Build GARM images" + runs-on: ubuntu-22.04 + steps: + - name: "Checkout" + uses: actions/checkout@v3 + with: + path: src/github.com/cloudbase/garm + fetch-depth: 0 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + + - name: Login to GitHub Container Registry + uses: docker/login-action@v2 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push + run: | + cd src/github.com/cloudbase/garm + VERSION=$(git describe --tags --match='v[0-9]*' --always ${{ github.event.inputs.ref }}) + docker buildx build \ + --provenance=false \ + --platform linux/amd64,linux/arm64 \ + --build-arg="GARM_REF=${{ github.event.inputs.ref }}" \ + -t ${{ github.event.inputs.push_to_project }}/garm:"${VERSION}" \ + --push . \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 860c6ce6..80d9b2a7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,29 @@ -FROM docker.io/golang:alpine +FROM docker.io/golang:alpine AS builder +ARG GARM_REF -WORKDIR /root -USER root +LABEL stage=builder -RUN apk add musl-dev gcc libtool m4 autoconf g++ make libblkid util-linux-dev git linux-headers mingw-w64-gcc +RUN apk add musl-dev gcc libtool m4 autoconf g++ make libblkid util-linux-dev git linux-headers +RUN git config --global --add safe.directory /build -ADD ./scripts/build-static.sh /build-static.sh -RUN chmod +x /build-static.sh +ADD . /build/garm +RUN cd /build/garm && git checkout ${GARM_REF} +RUN git clone https://github.com/cloudbase/garm-provider-azure /build/garm-provider-azure +RUN git clone https://github.com/cloudbase/garm-provider-openstack /build/garm-provider-openstack -CMD ["/bin/sh"] +RUN cd /build/garm && go build -o /bin/garm \ + -tags osusergo,netgo,sqlite_omit_load_extension \ + -ldflags "-linkmode external -extldflags '-static' -s -w -X main.Version=$(git describe --tags --match='v[0-9]*' --dirty --always)" \ + /build/garm/cmd/garm +RUN mkdir -p /opt/garm/providers.d +RUN cd /build/garm-provider-azure && go build -ldflags="-linkmode external -extldflags '-static' -s -w" -o /opt/garm/providers.d/garm-provider-azure . +RUN cd /build/garm-provider-openstack && go build -ldflags="-linkmode external -extldflags '-static' -s -w" -o /opt/garm/providers.d/garm-provider-openstack . + +FROM scratch + +COPY --from=builder /bin/garm /bin/garm +COPY --from=builder /opt/garm/providers.d/garm-provider-openstack /opt/garm/providers.d/garm-provider-openstack +COPY --from=builder /opt/garm/providers.d/garm-provider-azure /opt/garm/providers.d/garm-provider-azure +COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ + +ENTRYPOINT ["/bin/garm", "-config", "/etc/garm/config.toml"] diff --git a/Dockerfile.build-static b/Dockerfile.build-static new file mode 100644 index 00000000..ae023b71 --- /dev/null +++ b/Dockerfile.build-static @@ -0,0 +1,15 @@ +FROM docker.io/golang:alpine + +WORKDIR /root +USER root + +RUN apk add musl-dev gcc libtool m4 autoconf g++ make libblkid util-linux-dev git linux-headers mingw-w64-gcc + +RUN wget http://musl.cc/aarch64-linux-musl-cross.tgz -O /tmp/aarch64-linux-musl-cross.tgz && \ + tar --strip-components=1 -C /usr/local -xzf /tmp/aarch64-linux-musl-cross.tgz && \ + rm /tmp/aarch64-linux-musl-cross.tgz + +ADD ./scripts/build-static.sh /build-static.sh +RUN chmod +x /build-static.sh + +CMD ["/bin/sh"] diff --git a/Makefile b/Makefile index fbd2dbf2..b965d598 100644 --- a/Makefile +++ b/Makefile @@ -15,7 +15,7 @@ default: build .PHONY : build-static test install-lint-deps lint go-test fmt fmtcheck verify-vendor verify build-static: @echo Building garm - docker build --tag $(IMAGE_TAG) . + docker build --tag $(IMAGE_TAG) -f Dockerfile.build-static . docker run --rm -e USER_ID=$(USER_ID) -e USER_GROUP=$(USER_GROUP) -v $(PWD):/build/garm:z $(IMAGE_TAG) /build-static.sh @echo Binaries are available in $(PWD)/bin diff --git a/README.md b/README.md index 03930a78..8e53094e 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,14 @@ -# GitHub Actions Runner Manager (garm) +# GitHub Actions Runner Manager (GARM) [![Go Tests](https://github.com/cloudbase/garm/actions/workflows/go-tests.yml/badge.svg)](https://github.com/cloudbase/garm/actions/workflows/go-tests.yml) -Welcome to garm! +Welcome to GARM! Garm enables you to create and automatically maintain pools of [self-hosted GitHub runners](https://docs.github.com/en/actions/hosting-your-own-runners/about-self-hosted-runners), with autoscaling that can be used inside your github workflow runs. -The goal of ```garm``` is to be simple to set up, simple to configure and simple to use. It is a single binary that can run on any GNU/Linux machine without any other requirements other than the providers it creates the runners in. It is intended to be easy to deploy in any environment and can create runners in any system you can write a provider for. There is no complicated setup process and no extremely complex concepts to understand. Once set up, it's meant to stay out of your way. +The goal of ```GARM``` is to be simple to set up, simple to configure and simple to use. It is a single binary that can run on any GNU/Linux machine without any other requirements other than the providers it creates the runners in. It is intended to be easy to deploy in any environment and can create runners in any system you can write a provider for. There is no complicated setup process and no extremely complex concepts to understand. Once set up, it's meant to stay out of your way. -Garm supports creating pools on either GitHub itself or on your own deployment of [GitHub Enterprise Server](https://docs.github.com/en/enterprise-server@3.5/admin/overview/about-github-enterprise-server). For instructions on how to use ```garm``` with GHE, see the [credentials](/doc/github_credentials.md) section of the documentation. +Garm supports creating pools on either GitHub itself or on your own deployment of [GitHub Enterprise Server](https://docs.github.com/en/enterprise-server@3.5/admin/overview/about-github-enterprise-server). For instructions on how to use ```GARM``` with GHE, see the [credentials](/doc/github_credentials.md) section of the documentation. ## Join us on slack @@ -18,121 +18,36 @@ Whether you're running into issues or just want to drop by and say "hi", feel fr ## Installing -## Build from source +Check out the [quickstart](/doc/quickstart.md) document for instructions on how to install ```GARM```. If you'd like to build from source, check out the [building from source](/doc/building_from_source.md) document. -You need to have Go installed, then run: +## Installing external providers - ```bash - git clone https://github.com/cloudbase/garm - cd garm - go install ./... - ``` +External providers are binaries that GARM calls into to create runners in a particular IaaS. There are currently two external providers available: -You should now have both ```garm``` and ```garm-cli``` in your ```$GOPATH/bin``` folder. +* [OpenStack](https://github.com/cloudbase/garm-provider-openstack) +* [Azure](https://github.com/cloudbase/garm-provider-azure) -If you have docker/podman installed, you can also build statically linked binaries by running: - - ```bash - make build-static - ``` - -The ```garm``` and ```garm-cli``` binaries will be built and copied to the ```bin/``` folder in your current working directory. - -## Install the service - -Add a new system user: - - ```bash - useradd --shell /usr/bin/false \ - --system \ - --groups lxd \ - --no-create-home garm - ``` - -The ```lxd``` group is only needed if you have a local LXD install and want to connect to the unix socket to use it. If you're connecting to a remote LXD server over TCP, you can skip adding the ```garm``` user to the ```lxd``` group. - -Copy the binary to somewhere in the system ```$PATH```: - - ```bash - sudo cp $(go env GOPATH)/bin/garm /usr/local/bin/garm - ``` - -Or if you built garm using ```make```: - - ```bash - sudo cp ./bin/garm /usr/local/bin/garm - ``` - -Create the config folder: - - ```bash - sudo mkdir -p /etc/garm - ``` - -Copy the config template: - - ```bash - sudo cp ./testdata/config.toml /etc/garm/ - ``` - -Copy the external provider (optional): - - ```bash - sudo cp -a ./contrib/providers.d /etc/garm/ - ``` - -Copy the systemd service file: - - ```bash - sudo cp ./contrib/garm.service /etc/systemd/system/ - ``` - -Change permissions on config folder: - - ```bash - sudo chown -R garm:garm /etc/garm - sudo chmod 750 -R /etc/garm - ``` - -Enable the service: - - ```bash - sudo systemctl enable garm - ``` - -Customize the config in ```/etc/garm/config.toml```, and start the service: - - ```bash - sudo systemctl start garm - ``` +Follow the instructions in the README of each provider to install them. ## Configuration -The ```garm``` configuration is a simple ```toml```. A sample of the config file can be found in [the testdata folder](/testdata/config.toml). - -There are 3 major sections of the config that require your attention: - -* [Github credentials section](/doc/github_credentials.md) -* [Providers section](/doc/providers.md) -* [The database section](/doc/database.md) - -Once you've configured your database, providers and github credentials, you'll need to configure your [webhooks and the callback_url](/doc/webhooks_and_callbacks.md). - -At this point, you should be done. Have a look at the [running garm document](/doc/running_garm.md) for usage instructions and available features. - -If you would like to use ```garm``` with a different IaaS than the ones already available, have a look at the [writing an external provider](/doc/external_provider.md) page. - -If you like to optimize the startup time of new instance, take a look at the [performance considerations](/doc/performance_considerations.md) page. +The ```GARM``` configuration is a simple ```toml```. The sample config file in [the testdata folder](/testdata/config.toml) is fairly well commented and should be enough to get you started. The configuration file is split into several sections, each of which is documented in its own page. The sections are: -## Security considerations +* [The default section](/doc/config_default.md) +* [Database](/doc/database.md) +* [Github credentials](/doc/github_credentials.md) +* [Providers](/doc/providers.md) +* [Metrics](/doc/config_metrics.md) +* [JWT authentication](/doc/config_jwt_auth.md) +* [API server](/doc/config_api_server.md) -Garm does not apply any ACLs of any kind to the instances it creates. That task remains in the responsibility of the user. [Here is a guide for creating ACLs in LXD](https://linuxcontainers.org/lxd/docs/master/howto/network_acls/). You can of course use ```iptables``` or ```nftables``` to create any rules you wish. I recommend you create a separate isolated lxd bridge for runners, and secure it using ACLs/iptables/nftables. +## Optimizing your runners -You must make sure that the code that runs as part of the workflows is trusted, and if that cannot be done, you must make sure that any malicious code that will be pulled in by the actions and run as part of a workload, is as contained as possible. There is a nice article about [securing your workflow runs here](https://blog.gitguardian.com/github-actions-security-cheat-sheet/). +If you would like to optimize the startup time of new instance, take a look at the [performance considerations](/doc/performance_considerations.md) page. ## Write your own provider -The providers are interfaces between ```garm``` and a particular IaaS in which we spin up GitHub Runners. These providers can be either **native** or **external**. The **native** providers are written in ```Go```, and must implement [the interface defined here](https://github.com/cloudbase/garm/blob/main/runner/common/provider.go#L22-L39). **External** providers can be written in any language, as they are in the form of an external executable that ```garm``` calls into. +The providers are interfaces between ```GARM``` and a particular IaaS in which we spin up GitHub Runners. These providers can be either **native** or **external**. The **native** providers are written in ```Go```, and must implement [the interface defined here](https://github.com/cloudbase/garm/blob/main/runner/common/provider.go#L22-L39). **External** providers can be written in any language, as they are in the form of an external executable that ```GARM``` calls into. There is currently one **native** provider for [LXD](https://linuxcontainers.org/lxd/) and two **external** providers for [Openstack and Azure](/contrib/providers.d/). diff --git a/apiserver/controllers/controllers.go b/apiserver/controllers/controllers.go index a7257340..2c1fd42a 100644 --- a/apiserver/controllers/controllers.go +++ b/apiserver/controllers/controllers.go @@ -21,13 +21,13 @@ import ( "net/http" "strings" + gErrors "github.com/cloudbase/garm-provider-common/errors" + "github.com/cloudbase/garm-provider-common/util" "github.com/cloudbase/garm/apiserver/params" "github.com/cloudbase/garm/auth" - gErrors "github.com/cloudbase/garm/errors" "github.com/cloudbase/garm/metrics" runnerParams "github.com/cloudbase/garm/params" "github.com/cloudbase/garm/runner" - "github.com/cloudbase/garm/util" wsWriter "github.com/cloudbase/garm/websocket" "github.com/gorilla/websocket" @@ -202,6 +202,13 @@ func (a *APIController) NotFoundHandler(w http.ResponseWriter, r *http.Request) } } +// swagger:route GET /metrics-token metrics-token GetMetricsToken +// +// Returns a JWT token that can be used to access the metrics endpoint. +// +// Responses: +// 200: JWTResponse +// 401: APIErrorResponse func (a *APIController) MetricsTokenHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -222,6 +229,21 @@ func (a *APIController) MetricsTokenHandler(w http.ResponseWriter, r *http.Reque } } +// swagger:route POST /auth/login login Login +// +// Logs in a user and returns a JWT token. +// +// Parameters: +// + name: Body +// description: Login information. +// type: PasswordLoginParams +// in: body +// required: true +// +// Responses: +// 200: JWTResponse +// 400: APIErrorResponse +// // LoginHandler returns a jwt token func (a *APIController) LoginHandler(w http.ResponseWriter, r *http.Request) { var loginInfo runnerParams.PasswordLoginParams @@ -253,6 +275,20 @@ func (a *APIController) LoginHandler(w http.ResponseWriter, r *http.Request) { } } +// swagger:route POST /first-run first-run FirstRun +// +// Initialize the first run of the controller. +// +// Parameters: +// + name: Body +// description: Create a new user. +// type: NewUserParams +// in: body +// required: true +// +// Responses: +// 200: User +// 400: APIErrorResponse func (a *APIController) FirstRunHandler(w http.ResponseWriter, r *http.Request) { if a.auth.IsInitialized() { err := gErrors.NewConflictError("already initialized") @@ -279,6 +315,13 @@ 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) @@ -293,6 +336,13 @@ func (a *APIController) ListCredentials(w http.ResponseWriter, r *http.Request) } } +// swagger:route GET /providers providers ListProviders +// +// List all providers. +// +// Responses: +// 200: Providers +// 400: APIErrorResponse func (a *APIController) ListProviders(w http.ResponseWriter, r *http.Request) { ctx := r.Context() providers, err := a.r.ListProviders(ctx) @@ -307,6 +357,13 @@ func (a *APIController) ListProviders(w http.ResponseWriter, r *http.Request) { } } +// swagger:route GET /jobs jobs ListJobs +// +// List all jobs. +// +// Responses: +// 200: Jobs +// 400: APIErrorResponse func (a *APIController) ListAllJobs(w http.ResponseWriter, r *http.Request) { ctx := r.Context() jobs, err := a.r.ListAllJobs(ctx) diff --git a/apiserver/controllers/enterprises.go b/apiserver/controllers/enterprises.go index 1a3c1b5d..6a015df2 100644 --- a/apiserver/controllers/enterprises.go +++ b/apiserver/controllers/enterprises.go @@ -19,13 +19,27 @@ import ( "log" "net/http" + gErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/apiserver/params" - gErrors "github.com/cloudbase/garm/errors" runnerParams "github.com/cloudbase/garm/params" "github.com/gorilla/mux" ) +// swagger:route POST /enterprises enterprises CreateEnterprise +// +// Create enterprise with the given parameters. +// +// Parameters: +// + name: Body +// description: Parameters used to create the enterprise. +// type: CreateEnterpriseParams +// in: body +// required: true +// +// Responses: +// 200: Enterprise +// default: APIErrorResponse func (a *APIController) CreateEnterpriseHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -48,6 +62,13 @@ func (a *APIController) CreateEnterpriseHandler(w http.ResponseWriter, r *http.R } } +// swagger:route GET /enterprises enterprises ListEnterprises +// +// List all enterprises. +// +// Responses: +// 200: Enterprises +// default: APIErrorResponse func (a *APIController) ListEnterprisesHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -64,6 +85,20 @@ func (a *APIController) ListEnterprisesHandler(w http.ResponseWriter, r *http.Re } } +// swagger:route GET /enterprises/{enterpriseID} enterprises GetEnterprise +// +// Get enterprise by ID. +// +// Parameters: +// + name: enterpriseID +// description: The ID of the enterprise to fetch. +// type: string +// in: path +// required: true +// +// Responses: +// 200: Enterprise +// default: APIErrorResponse func (a *APIController) GetEnterpriseByIDHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -93,6 +128,19 @@ func (a *APIController) GetEnterpriseByIDHandler(w http.ResponseWriter, r *http. } } +// swagger:route DELETE /enterprises/{enterpriseID} enterprises DeleteEnterprise +// +// Delete enterprise by ID. +// +// Parameters: +// + name: enterpriseID +// description: ID of the enterprise to delete. +// type: string +// in: path +// required: true +// +// Responses: +// default: APIErrorResponse func (a *APIController) DeleteEnterpriseHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -120,6 +168,25 @@ func (a *APIController) DeleteEnterpriseHandler(w http.ResponseWriter, r *http.R } +// swagger:route PUT /enterprises/{enterpriseID} enterprises UpdateEnterprise +// +// Update enterprise with the given parameters. +// +// Parameters: +// + name: enterpriseID +// description: The ID of the enterprise to update. +// type: string +// in: path +// required: true +// + name: Body +// description: Parameters used when updating the enterprise. +// type: UpdateEntityParams +// in: body +// required: true +// +// Responses: +// 200: Enterprise +// default: APIErrorResponse func (a *APIController) UpdateEnterpriseHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -155,6 +222,26 @@ func (a *APIController) UpdateEnterpriseHandler(w http.ResponseWriter, r *http.R } } +// swagger:route POST /enterprises/{enterpriseID}/pools enterprises pools CreateEnterprisePool +// +// Create enterprise pool with the parameters given. +// +// Parameters: +// + name: enterpriseID +// description: Enterprise ID. +// type: string +// in: path +// required: true +// +// + name: Body +// description: Parameters used when creating the enterprise pool. +// type: CreatePoolParams +// in: body +// required: true +// +// Responses: +// 200: Pool +// default: APIErrorResponse func (a *APIController) CreateEnterprisePoolHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -191,6 +278,20 @@ func (a *APIController) CreateEnterprisePoolHandler(w http.ResponseWriter, r *ht } } +// swagger:route GET /enterprises/{enterpriseID}/pools enterprises pools ListEnterprisePools +// +// List enterprise pools. +// +// Parameters: +// + name: enterpriseID +// description: Enterprise ID. +// type: string +// in: path +// required: true +// +// Responses: +// 200: Pools +// default: APIErrorResponse func (a *APIController) ListEnterprisePoolsHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() vars := mux.Vars(r) @@ -220,6 +321,26 @@ func (a *APIController) ListEnterprisePoolsHandler(w http.ResponseWriter, r *htt } +// swagger:route GET /enterprises/{enterpriseID}/pools/{poolID} enterprises pools GetEnterprisePool +// +// Get enterprise pool by ID. +// +// Parameters: +// + name: enterpriseID +// description: Enterprise ID. +// type: string +// in: path +// required: true +// +// + name: poolID +// description: Pool ID. +// type: string +// in: path +// required: true +// +// Responses: +// 200: Pool +// default: APIErrorResponse func (a *APIController) GetEnterprisePoolHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() vars := mux.Vars(r) @@ -249,6 +370,25 @@ func (a *APIController) GetEnterprisePoolHandler(w http.ResponseWriter, r *http. } } +// swagger:route DELETE /enterprises/{enterpriseID}/pools/{poolID} enterprises pools DeleteEnterprisePool +// +// Delete enterprise pool by ID. +// +// Parameters: +// + name: enterpriseID +// description: Enterprise ID. +// type: string +// in: path +// required: true +// +// + name: poolID +// description: ID of the enterprise pool to delete. +// type: string +// in: path +// required: true +// +// Responses: +// default: APIErrorResponse func (a *APIController) DeleteEnterprisePoolHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -277,6 +417,32 @@ func (a *APIController) DeleteEnterprisePoolHandler(w http.ResponseWriter, r *ht } +// swagger:route PUT /enterprises/{enterpriseID}/pools/{poolID} enterprises pools UpdateEnterprisePool +// +// Update enterprise pool with the parameters given. +// +// Parameters: +// + name: enterpriseID +// description: Enterprise ID. +// type: string +// in: path +// required: true +// +// + name: poolID +// description: ID of the enterprise pool to update. +// type: string +// in: path +// required: true +// +// + name: Body +// description: Parameters used when updating the enterprise pool. +// type: UpdatePoolParams +// in: body +// required: true +// +// Responses: +// 200: Pool +// default: APIErrorResponse func (a *APIController) UpdateEnterprisePoolHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() diff --git a/apiserver/controllers/instances.go b/apiserver/controllers/instances.go index c867c523..e4011b3e 100644 --- a/apiserver/controllers/instances.go +++ b/apiserver/controllers/instances.go @@ -19,13 +19,27 @@ import ( "log" "net/http" + gErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/apiserver/params" - gErrors "github.com/cloudbase/garm/errors" runnerParams "github.com/cloudbase/garm/params" "github.com/gorilla/mux" ) +// swagger:route GET /pools/{poolID}/instances instances ListPoolInstances +// +// List runner instances in a pool. +// +// Parameters: +// + name: poolID +// description: Runner pool ID. +// type: string +// in: path +// required: true +// +// Responses: +// 200: Instances +// default: APIErrorResponse func (a *APIController) ListPoolInstancesHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() vars := mux.Vars(r) @@ -176,6 +190,20 @@ func (a *APIController) ListRepoInstancesHandler(w http.ResponseWriter, r *http. } } +// swagger:route GET /organizations/{orgID}/instances organizations instances ListOrgInstances +// +// List organization instances. +// +// Parameters: +// + name: orgID +// description: Organization ID. +// type: string +// in: path +// required: true +// +// Responses: +// 200: Instances +// default: APIErrorResponse func (a *APIController) ListOrgInstancesHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() vars := mux.Vars(r) @@ -204,6 +232,20 @@ func (a *APIController) ListOrgInstancesHandler(w http.ResponseWriter, r *http.R } } +// swagger:route GET /enterprises/{enterpriseID}/instances enterprises instances ListEnterpriseInstances +// +// List enterprise instances. +// +// Parameters: +// + name: enterpriseID +// description: Enterprise ID. +// type: string +// in: path +// required: true +// +// Responses: +// 200: Instances +// default: APIErrorResponse func (a *APIController) ListEnterpriseInstancesHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() vars := mux.Vars(r) diff --git a/apiserver/controllers/organizations.go b/apiserver/controllers/organizations.go index 7cdb072b..d03d1de4 100644 --- a/apiserver/controllers/organizations.go +++ b/apiserver/controllers/organizations.go @@ -19,13 +19,27 @@ import ( "log" "net/http" + gErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/apiserver/params" - gErrors "github.com/cloudbase/garm/errors" runnerParams "github.com/cloudbase/garm/params" "github.com/gorilla/mux" ) +// swagger:route POST /organizations organizations CreateOrg +// +// Create organization with the parameters given. +// +// Parameters: +// + name: Body +// description: Parameters used when creating the organization. +// type: CreateOrgParams +// in: body +// required: true +// +// Responses: +// 200: Organization +// default: APIErrorResponse func (a *APIController) CreateOrgHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -48,6 +62,13 @@ func (a *APIController) CreateOrgHandler(w http.ResponseWriter, r *http.Request) } } +// swagger:route GET /organizations organizations ListOrgs +// +// List organizations. +// +// Responses: +// 200: Organizations +// default: APIErrorResponse func (a *APIController) ListOrgsHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -64,6 +85,20 @@ func (a *APIController) ListOrgsHandler(w http.ResponseWriter, r *http.Request) } } +// swagger:route GET /organizations/{orgID} organizations GetOrg +// +// Get organization by ID. +// +// Parameters: +// + name: orgID +// description: ID of the organization to fetch. +// type: string +// in: path +// required: true +// +// Responses: +// 200: Organization +// default: APIErrorResponse func (a *APIController) GetOrgByIDHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -93,6 +128,19 @@ func (a *APIController) GetOrgByIDHandler(w http.ResponseWriter, r *http.Request } } +// swagger:route DELETE /organizations/{orgID} organizations DeleteOrg +// +// Delete organization by ID. +// +// Parameters: +// + name: orgID +// description: ID of the organization to delete. +// type: string +// in: path +// required: true +// +// Responses: +// default: APIErrorResponse func (a *APIController) DeleteOrgHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -120,6 +168,26 @@ func (a *APIController) DeleteOrgHandler(w http.ResponseWriter, r *http.Request) } +// swagger:route PUT /organizations/{orgID} organizations UpdateOrg +// +// Update organization with the parameters given. +// +// Parameters: +// + name: orgID +// description: ID of the organization to update. +// type: string +// in: path +// required: true +// +// + name: Body +// description: Parameters used when updating the organization. +// type: UpdateEntityParams +// in: body +// required: true +// +// Responses: +// 200: Organization +// default: APIErrorResponse func (a *APIController) UpdateOrgHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -155,6 +223,26 @@ func (a *APIController) UpdateOrgHandler(w http.ResponseWriter, r *http.Request) } } +// swagger:route POST /organizations/{orgID}/pools organizations pools CreateOrgPool +// +// Create organization pool with the parameters given. +// +// Parameters: +// + name: orgID +// description: Organization ID. +// type: string +// in: path +// required: true +// +// + name: Body +// description: Parameters used when creating the organization pool. +// type: CreatePoolParams +// in: body +// required: true +// +// Responses: +// 200: Pool +// default: APIErrorResponse func (a *APIController) CreateOrgPoolHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -191,6 +279,20 @@ func (a *APIController) CreateOrgPoolHandler(w http.ResponseWriter, r *http.Requ } } +// swagger:route GET /organizations/{orgID}/pools organizations pools ListOrgPools +// +// List organization pools. +// +// Parameters: +// + name: orgID +// description: Organization ID. +// type: string +// in: path +// required: true +// +// Responses: +// 200: Pools +// default: APIErrorResponse func (a *APIController) ListOrgPoolsHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() vars := mux.Vars(r) @@ -219,6 +321,26 @@ func (a *APIController) ListOrgPoolsHandler(w http.ResponseWriter, r *http.Reque } } +// swagger:route GET /organizations/{orgID}/pools/{poolID} organizations pools GetOrgPool +// +// Get organization pool by ID. +// +// Parameters: +// + name: orgID +// description: Organization ID. +// type: string +// in: path +// required: true +// +// + name: poolID +// description: Pool ID. +// type: string +// in: path +// required: true +// +// Responses: +// 200: Pool +// default: APIErrorResponse func (a *APIController) GetOrgPoolHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() vars := mux.Vars(r) @@ -248,6 +370,25 @@ func (a *APIController) GetOrgPoolHandler(w http.ResponseWriter, r *http.Request } } +// swagger:route DELETE /organizations/{orgID}/pools/{poolID} organizations pools DeleteOrgPool +// +// Delete organization pool by ID. +// +// Parameters: +// + name: orgID +// description: Organization ID. +// type: string +// in: path +// required: true +// +// + name: poolID +// description: ID of the organization pool to delete. +// type: string +// in: path +// required: true +// +// Responses: +// default: APIErrorResponse func (a *APIController) DeleteOrgPoolHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -276,6 +417,32 @@ func (a *APIController) DeleteOrgPoolHandler(w http.ResponseWriter, r *http.Requ } +// swagger:route PUT /organizations/{orgID}/pools/{poolID} organizations pools UpdateOrgPool +// +// Update organization pool with the parameters given. +// +// Parameters: +// + name: orgID +// description: Organization ID. +// type: string +// in: path +// required: true +// +// + name: poolID +// description: ID of the organization pool to update. +// type: string +// in: path +// required: true +// +// + name: Body +// description: Parameters used when updating the organization pool. +// type: UpdatePoolParams +// in: body +// required: true +// +// Responses: +// 200: Pool +// default: APIErrorResponse func (a *APIController) UpdateOrgPoolHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() diff --git a/apiserver/controllers/pools.go b/apiserver/controllers/pools.go index b4e5ffa2..34403759 100644 --- a/apiserver/controllers/pools.go +++ b/apiserver/controllers/pools.go @@ -19,13 +19,20 @@ import ( "log" "net/http" + gErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/apiserver/params" - gErrors "github.com/cloudbase/garm/errors" runnerParams "github.com/cloudbase/garm/params" "github.com/gorilla/mux" ) +// swagger:route GET /pools pools ListPools +// +// List all pools. +// +// Responses: +// 200: Pools +// default: APIErrorResponse func (a *APIController) ListAllPoolsHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -43,6 +50,20 @@ func (a *APIController) ListAllPoolsHandler(w http.ResponseWriter, r *http.Reque } } +// swagger:route GET /pools/{poolID} pools GetPool +// +// Get pool by ID. +// +// Parameters: +// + name: poolID +// description: ID of the pool to fetch. +// type: string +// in: path +// required: true +// +// Responses: +// 200: Pool +// default: APIErrorResponse func (a *APIController) GetPoolByIDHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -74,6 +95,19 @@ func (a *APIController) GetPoolByIDHandler(w http.ResponseWriter, r *http.Reques } } +// swagger:route DELETE /pools/{poolID} pools DeletePool +// +// Delete pool by ID. +// +// Parameters: +// + name: poolID +// description: ID of the pool to delete. +// type: string +// in: path +// required: true +// +// Responses: +// default: APIErrorResponse func (a *APIController) DeletePoolByIDHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -100,6 +134,26 @@ func (a *APIController) DeletePoolByIDHandler(w http.ResponseWriter, r *http.Req w.WriteHeader(http.StatusOK) } +// swagger:route PUT /pools/{poolID} pools UpdatePool +// +// Update pool by ID. +// +// Parameters: +// + name: poolID +// description: ID of the pool to update. +// type: string +// in: path +// required: true +// +// + name: Body +// description: Parameters to update the pool with. +// type: UpdatePoolParams +// in: body +// required: true +// +// Responses: +// 200: Pool +// default: APIErrorResponse func (a *APIController) UpdatePoolByIDHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() diff --git a/apiserver/controllers/repositories.go b/apiserver/controllers/repositories.go index 71b46e12..9aae826f 100644 --- a/apiserver/controllers/repositories.go +++ b/apiserver/controllers/repositories.go @@ -19,8 +19,8 @@ import ( "log" "net/http" + gErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/apiserver/params" - gErrors "github.com/cloudbase/garm/errors" runnerParams "github.com/cloudbase/garm/params" "github.com/gorilla/mux" diff --git a/apiserver/routers/routers.go b/apiserver/routers/routers.go index cdb9c3eb..55e42684 100644 --- a/apiserver/routers/routers.go +++ b/apiserver/routers/routers.go @@ -54,9 +54,9 @@ import ( "github.com/gorilla/mux" "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/cloudbase/garm-provider-common/util" "github.com/cloudbase/garm/apiserver/controllers" "github.com/cloudbase/garm/auth" - "github.com/cloudbase/garm/util" ) func WithMetricsRouter(parentRouter *mux.Router, disableAuth bool, metricsMiddlerware auth.Middleware) *mux.Router { @@ -98,6 +98,7 @@ func NewAPIRouter(han *controllers.APIController, logWriter io.Writer, authMiddl // FirstRunHandler firstRunRouter := apiSubRouter.PathPrefix("/first-run").Subrouter() firstRunRouter.Handle("/", http.HandlerFunc(han.FirstRunHandler)).Methods("POST", "OPTIONS") + firstRunRouter.Handle("", http.HandlerFunc(han.FirstRunHandler)).Methods("POST", "OPTIONS") // Instance URLs callbackRouter := apiSubRouter.PathPrefix("/callbacks").Subrouter() @@ -219,7 +220,7 @@ func NewAPIRouter(han *controllers.APIController, logWriter io.Writer, authMiddl apiRouter.Handle("/organizations/{orgID}/pools/", http.HandlerFunc(han.CreateOrgPoolHandler)).Methods("POST", "OPTIONS") apiRouter.Handle("/organizations/{orgID}/pools", http.HandlerFunc(han.CreateOrgPoolHandler)).Methods("POST", "OPTIONS") - // Repo instances list + // Org instances list apiRouter.Handle("/organizations/{orgID}/instances/", http.HandlerFunc(han.ListOrgInstancesHandler)).Methods("GET", "OPTIONS") apiRouter.Handle("/organizations/{orgID}/instances", http.HandlerFunc(han.ListOrgInstancesHandler)).Methods("GET", "OPTIONS") @@ -258,23 +259,23 @@ func NewAPIRouter(han *controllers.APIController, logWriter io.Writer, authMiddl apiRouter.Handle("/enterprises/{enterpriseID}/pools/", http.HandlerFunc(han.CreateEnterprisePoolHandler)).Methods("POST", "OPTIONS") apiRouter.Handle("/enterprises/{enterpriseID}/pools", http.HandlerFunc(han.CreateEnterprisePoolHandler)).Methods("POST", "OPTIONS") - // Repo instances list + // Enterprise instances list apiRouter.Handle("/enterprises/{enterpriseID}/instances/", http.HandlerFunc(han.ListEnterpriseInstancesHandler)).Methods("GET", "OPTIONS") apiRouter.Handle("/enterprises/{enterpriseID}/instances", http.HandlerFunc(han.ListEnterpriseInstancesHandler)).Methods("GET", "OPTIONS") - // Get org + // Get enterprise apiRouter.Handle("/enterprises/{enterpriseID}/", http.HandlerFunc(han.GetEnterpriseByIDHandler)).Methods("GET", "OPTIONS") apiRouter.Handle("/enterprises/{enterpriseID}", http.HandlerFunc(han.GetEnterpriseByIDHandler)).Methods("GET", "OPTIONS") - // Update org + // Update enterprise apiRouter.Handle("/enterprises/{enterpriseID}/", http.HandlerFunc(han.UpdateEnterpriseHandler)).Methods("PUT", "OPTIONS") apiRouter.Handle("/enterprises/{enterpriseID}", http.HandlerFunc(han.UpdateEnterpriseHandler)).Methods("PUT", "OPTIONS") - // Delete org + // Delete enterprise apiRouter.Handle("/enterprises/{enterpriseID}/", http.HandlerFunc(han.DeleteEnterpriseHandler)).Methods("DELETE", "OPTIONS") apiRouter.Handle("/enterprises/{enterpriseID}", http.HandlerFunc(han.DeleteEnterpriseHandler)).Methods("DELETE", "OPTIONS") - // List orgs + // List enterprises apiRouter.Handle("/enterprises/", http.HandlerFunc(han.ListEnterprisesHandler)).Methods("GET", "OPTIONS") apiRouter.Handle("/enterprises", http.HandlerFunc(han.ListEnterprisesHandler)).Methods("GET", "OPTIONS") - // Create org + // Create enterprise apiRouter.Handle("/enterprises/", http.HandlerFunc(han.CreateEnterpriseHandler)).Methods("POST", "OPTIONS") apiRouter.Handle("/enterprises", http.HandlerFunc(han.CreateEnterpriseHandler)).Methods("POST", "OPTIONS") diff --git a/apiserver/swagger-models.yaml b/apiserver/swagger-models.yaml index 9565aff5..417f178a 100644 --- a/apiserver/swagger-models.yaml +++ b/apiserver/swagger-models.yaml @@ -1,13 +1,91 @@ # NOTE: The purpose of these definitions is to reuse the existing golang # types from GARM packages. definitions: - Instances: + User: + type: object + x-go-type: + type: User + import: + package: github.com/cloudbase/garm/params + alias: garm_params + NewUserParams: + type: object + x-go-type: + type: NewUserParams + import: + package: github.com/cloudbase/garm/params + alias: garm_params + PasswordLoginParams: + type: object + x-go-type: + type: PasswordLoginParams + import: + package: github.com/cloudbase/garm/params + alias: garm_params + JWTResponse: + type: object + x-go-type: + type: JWTResponse + import: + package: github.com/cloudbase/garm/params + alias: garm_params + Jobs: + type: array + x-go-type: + type: Jobs + import: + package: github.com/cloudbase/garm/params + alias: garm_params + items: + $ref: '#/definitions/Job' + Job: type: object + x-go-type: + type: Job + import: + package: github.com/cloudbase/garm/params + alias: garm_params + Credentials: + type: array + x-go-type: + type: Credentials + import: + package: github.com/cloudbase/garm/params + alias: garm_params + items: + $ref: '#/definitions/GithubCredentials' + GithubCredentials: + type: object + x-go-type: + type: GithubCredentials + import: + package: github.com/cloudbase/garm/params + alias: garm_params + Providers: + type: array + x-go-type: + type: Providers + import: + package: github.com/cloudbase/garm/params + alias: garm_params + items: + $ref: '#/definitions/Provider' + Provider: + type: object + x-go-type: + type: Provider + import: + package: github.com/cloudbase/garm/params + alias: garm_params + Instances: + type: array x-go-type: type: Instances import: package: github.com/cloudbase/garm/params alias: garm_params + items: + $ref: '#/definitions/Instance' Instance: type: object x-go-type: @@ -16,12 +94,14 @@ definitions: package: github.com/cloudbase/garm/params alias: garm_params Pools: - type: object + type: array x-go-type: type: Pools import: package: github.com/cloudbase/garm/params alias: garm_params + items: + $ref: '#/definitions/Pool' Pool: type: object x-go-type: @@ -52,6 +132,52 @@ definitions: import: package: github.com/cloudbase/garm/params alias: garm_params + Organizations: + type: array + x-go-type: + type: Organizations + import: + package: github.com/cloudbase/garm/params + alias: garm_params + items: + $ref: '#/definitions/Organization' + Organization: + type: object + x-go-type: + type: Organization + import: + package: github.com/cloudbase/garm/params + alias: garm_params + CreateOrgParams: + type: object + x-go-type: + type: CreateOrgParams + import: + package: github.com/cloudbase/garm/params + alias: garm_params + Enterprises: + type: array + x-go-type: + type: Enterprises + import: + package: github.com/cloudbase/garm/params + alias: garm_params + items: + $ref: '#/definitions/Enterprise' + Enterprise: + type: object + x-go-type: + type: Enterprise + import: + package: github.com/cloudbase/garm/params + alias: garm_params + CreateEnterpriseParams: + type: object + x-go-type: + type: CreateEnterpriseParams + import: + package: github.com/cloudbase/garm/params + alias: garm_params UpdateEntityParams: type: object x-go-type: diff --git a/apiserver/swagger.yaml b/apiserver/swagger.yaml index acf2a42b..0da7dddf 100644 --- a/apiserver/swagger.yaml +++ b/apiserver/swagger.yaml @@ -9,6 +9,20 @@ definitions: alias: apiserver_params package: github.com/cloudbase/garm/apiserver/params type: APIErrorResponse + CreateEnterpriseParams: + type: object + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: CreateEnterpriseParams + CreateOrgParams: + type: object + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: CreateOrgParams CreatePoolParams: type: object x-go-type: @@ -23,6 +37,38 @@ definitions: alias: garm_params package: github.com/cloudbase/garm/params type: CreateRepoParams + Credentials: + items: + $ref: '#/definitions/GithubCredentials' + type: array + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: Credentials + Enterprise: + type: object + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: Enterprise + Enterprises: + items: + $ref: '#/definitions/Enterprise' + type: array + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: Enterprises + GithubCredentials: + type: object + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: GithubCredentials Instance: type: object x-go-type: @@ -31,12 +77,67 @@ definitions: package: github.com/cloudbase/garm/params type: Instance Instances: - type: object + items: + $ref: '#/definitions/Instance' + type: array x-go-type: import: alias: garm_params package: github.com/cloudbase/garm/params type: Instances + JWTResponse: + type: object + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: JWTResponse + Job: + type: object + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: Job + Jobs: + items: + $ref: '#/definitions/Job' + type: array + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: Jobs + NewUserParams: + type: object + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: NewUserParams + Organization: + type: object + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: Organization + Organizations: + items: + $ref: '#/definitions/Organization' + type: array + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: Organizations + PasswordLoginParams: + type: object + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: PasswordLoginParams Pool: type: object x-go-type: @@ -45,12 +146,30 @@ definitions: package: github.com/cloudbase/garm/params type: Pool Pools: - type: object + items: + $ref: '#/definitions/Pool' + type: array x-go-type: import: alias: garm_params package: github.com/cloudbase/garm/params type: Pools + Provider: + type: object + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: Provider + Providers: + items: + $ref: '#/definitions/Provider' + type: array + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: Providers Repositories: items: $ref: '#/definitions/Repository' @@ -81,6 +200,13 @@ definitions: alias: garm_params package: github.com/cloudbase/garm/params type: UpdatePoolParams + User: + type: object + x-go-type: + import: + alias: garm_params + package: github.com/cloudbase/garm/params + type: User info: description: The Garm API generated using go-swagger. license: @@ -89,9 +215,157 @@ info: title: Garm API. version: 1.0.0 paths: - /instances: + /auth/login: + post: + operationId: Login + parameters: + - description: Login information. + in: body + name: Body + required: true + schema: + $ref: '#/definitions/PasswordLoginParams' + description: Login information. + type: object + responses: + "200": + description: JWTResponse + schema: + $ref: '#/definitions/JWTResponse' + "400": + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Logs in a user and returns a JWT token. + tags: + - login + /credentials: get: - operationId: ListInstances + operationId: ListCredentials + responses: + "200": + description: Credentials + schema: + $ref: '#/definitions/Credentials' + "400": + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: List all credentials. + tags: + - credentials + /enterprises: + get: + operationId: ListEnterprises + responses: + "200": + description: Enterprises + schema: + $ref: '#/definitions/Enterprises' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: List all enterprises. + tags: + - enterprises + post: + operationId: CreateEnterprise + parameters: + - description: Parameters used to create the enterprise. + in: body + name: Body + required: true + schema: + $ref: '#/definitions/CreateEnterpriseParams' + description: Parameters used to create the enterprise. + type: object + responses: + "200": + description: Enterprise + schema: + $ref: '#/definitions/Enterprise' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Create enterprise with the given parameters. + tags: + - enterprises + /enterprises/{enterpriseID}: + delete: + operationId: DeleteEnterprise + parameters: + - description: ID of the enterprise to delete. + in: path + name: enterpriseID + required: true + type: string + responses: + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Delete enterprise by ID. + tags: + - enterprises + get: + operationId: GetEnterprise + parameters: + - description: The ID of the enterprise to fetch. + in: path + name: enterpriseID + required: true + type: string + responses: + "200": + description: Enterprise + schema: + $ref: '#/definitions/Enterprise' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Get enterprise by ID. + tags: + - enterprises + put: + operationId: UpdateEnterprise + parameters: + - description: The ID of the enterprise to update. + in: path + name: enterpriseID + required: true + type: string + - description: Parameters used when updating the enterprise. + in: body + name: Body + required: true + schema: + $ref: '#/definitions/UpdateEntityParams' + description: Parameters used when updating the enterprise. + type: object + responses: + "200": + description: Enterprise + schema: + $ref: '#/definitions/Enterprise' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Update enterprise with the given parameters. + tags: + - enterprises + /enterprises/{enterpriseID}/instances: + get: + operationId: ListEnterpriseInstances + parameters: + - description: Enterprise ID. + in: path + name: enterpriseID + required: true + type: string responses: "200": description: Instances @@ -101,16 +375,73 @@ paths: description: APIErrorResponse schema: $ref: '#/definitions/APIErrorResponse' - summary: Get all runners' instances. + summary: List enterprise instances. tags: + - enterprises - instances - /instances/{instanceName}: + /enterprises/{enterpriseID}/pools: + get: + operationId: ListEnterprisePools + parameters: + - description: Enterprise ID. + in: path + name: enterpriseID + required: true + type: string + responses: + "200": + description: Pools + schema: + $ref: '#/definitions/Pools' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: List enterprise pools. + tags: + - enterprises + - pools + post: + operationId: CreateEnterprisePool + parameters: + - description: Enterprise ID. + in: path + name: enterpriseID + required: true + type: string + - description: Parameters used when creating the enterprise pool. + in: body + name: Body + required: true + schema: + $ref: '#/definitions/CreatePoolParams' + description: Parameters used when creating the enterprise pool. + type: object + responses: + "200": + description: Pool + schema: + $ref: '#/definitions/Pool' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Create enterprise pool with the parameters given. + tags: + - enterprises + - pools + /enterprises/{enterpriseID}/pools/{poolID}: delete: - operationId: DeleteInstance + operationId: DeleteEnterprisePool parameters: - - description: Runner instance name. + - description: Enterprise ID. in: path - name: instanceName + name: enterpriseID + required: true + type: string + - description: ID of the enterprise pool to delete. + in: path + name: poolID required: true type: string responses: @@ -118,29 +449,551 @@ paths: description: APIErrorResponse schema: $ref: '#/definitions/APIErrorResponse' - summary: Delete runner instance by name. + summary: Delete enterprise pool by ID. tags: - - instances + - enterprises + - pools get: - operationId: GetInstance + operationId: GetEnterprisePool parameters: - - description: Runner instance name. + - description: Enterprise ID. in: path - name: instanceName + name: enterpriseID + required: true + type: string + - description: Pool ID. + in: path + name: poolID required: true type: string responses: "200": - description: Instance + description: Pool schema: - $ref: '#/definitions/Instance' + $ref: '#/definitions/Pool' default: description: APIErrorResponse schema: $ref: '#/definitions/APIErrorResponse' - summary: Get runner instance by name. + summary: Get enterprise pool by ID. tags: - - instances + - enterprises + - pools + put: + operationId: UpdateEnterprisePool + parameters: + - description: Enterprise ID. + in: path + name: enterpriseID + required: true + type: string + - description: ID of the enterprise pool to update. + in: path + name: poolID + required: true + type: string + - description: Parameters used when updating the enterprise pool. + in: body + name: Body + required: true + schema: + $ref: '#/definitions/UpdatePoolParams' + description: Parameters used when updating the enterprise pool. + type: object + responses: + "200": + description: Pool + schema: + $ref: '#/definitions/Pool' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Update enterprise pool with the parameters given. + tags: + - enterprises + - pools + /first-run: + post: + operationId: FirstRun + parameters: + - description: Create a new user. + in: body + name: Body + required: true + schema: + $ref: '#/definitions/NewUserParams' + description: Create a new user. + type: object + responses: + "200": + description: User + schema: + $ref: '#/definitions/User' + "400": + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Initialize the first run of the controller. + tags: + - first-run + /instances: + get: + operationId: ListInstances + responses: + "200": + description: Instances + schema: + $ref: '#/definitions/Instances' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Get all runners' instances. + tags: + - instances + /instances/{instanceName}: + delete: + operationId: DeleteInstance + parameters: + - description: Runner instance name. + in: path + name: instanceName + required: true + type: string + responses: + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Delete runner instance by name. + tags: + - instances + get: + operationId: GetInstance + parameters: + - description: Runner instance name. + in: path + name: instanceName + required: true + type: string + responses: + "200": + description: Instance + schema: + $ref: '#/definitions/Instance' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Get runner instance by name. + tags: + - instances + /jobs: + get: + operationId: ListJobs + responses: + "200": + description: Jobs + schema: + $ref: '#/definitions/Jobs' + "400": + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: List all jobs. + tags: + - jobs + /metrics-token: + get: + operationId: GetMetricsToken + responses: + "200": + description: JWTResponse + schema: + $ref: '#/definitions/JWTResponse' + "401": + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Returns a JWT token that can be used to access the metrics endpoint. + tags: + - metrics-token + /organizations: + get: + operationId: ListOrgs + responses: + "200": + description: Organizations + schema: + $ref: '#/definitions/Organizations' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: List organizations. + tags: + - organizations + post: + operationId: CreateOrg + parameters: + - description: Parameters used when creating the organization. + in: body + name: Body + required: true + schema: + $ref: '#/definitions/CreateOrgParams' + description: Parameters used when creating the organization. + type: object + responses: + "200": + description: Organization + schema: + $ref: '#/definitions/Organization' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Create organization with the parameters given. + tags: + - organizations + /organizations/{orgID}: + delete: + operationId: DeleteOrg + parameters: + - description: ID of the organization to delete. + in: path + name: orgID + required: true + type: string + responses: + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Delete organization by ID. + tags: + - organizations + get: + operationId: GetOrg + parameters: + - description: ID of the organization to fetch. + in: path + name: orgID + required: true + type: string + responses: + "200": + description: Organization + schema: + $ref: '#/definitions/Organization' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Get organization by ID. + tags: + - organizations + put: + operationId: UpdateOrg + parameters: + - description: ID of the organization to update. + in: path + name: orgID + required: true + type: string + - description: Parameters used when updating the organization. + in: body + name: Body + required: true + schema: + $ref: '#/definitions/UpdateEntityParams' + description: Parameters used when updating the organization. + type: object + responses: + "200": + description: Organization + schema: + $ref: '#/definitions/Organization' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Update organization with the parameters given. + tags: + - organizations + /organizations/{orgID}/instances: + get: + operationId: ListOrgInstances + parameters: + - description: Organization ID. + in: path + name: orgID + required: true + type: string + responses: + "200": + description: Instances + schema: + $ref: '#/definitions/Instances' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: List organization instances. + tags: + - organizations + - instances + /organizations/{orgID}/pools: + get: + operationId: ListOrgPools + parameters: + - description: Organization ID. + in: path + name: orgID + required: true + type: string + responses: + "200": + description: Pools + schema: + $ref: '#/definitions/Pools' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: List organization pools. + tags: + - organizations + - pools + post: + operationId: CreateOrgPool + parameters: + - description: Organization ID. + in: path + name: orgID + required: true + type: string + - description: Parameters used when creating the organization pool. + in: body + name: Body + required: true + schema: + $ref: '#/definitions/CreatePoolParams' + description: Parameters used when creating the organization pool. + type: object + responses: + "200": + description: Pool + schema: + $ref: '#/definitions/Pool' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Create organization pool with the parameters given. + tags: + - organizations + - pools + /organizations/{orgID}/pools/{poolID}: + delete: + operationId: DeleteOrgPool + parameters: + - description: Organization ID. + in: path + name: orgID + required: true + type: string + - description: ID of the organization pool to delete. + in: path + name: poolID + required: true + type: string + responses: + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Delete organization pool by ID. + tags: + - organizations + - pools + get: + operationId: GetOrgPool + parameters: + - description: Organization ID. + in: path + name: orgID + required: true + type: string + - description: Pool ID. + in: path + name: poolID + required: true + type: string + responses: + "200": + description: Pool + schema: + $ref: '#/definitions/Pool' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Get organization pool by ID. + tags: + - organizations + - pools + put: + operationId: UpdateOrgPool + parameters: + - description: Organization ID. + in: path + name: orgID + required: true + type: string + - description: ID of the organization pool to update. + in: path + name: poolID + required: true + type: string + - description: Parameters used when updating the organization pool. + in: body + name: Body + required: true + schema: + $ref: '#/definitions/UpdatePoolParams' + description: Parameters used when updating the organization pool. + type: object + responses: + "200": + description: Pool + schema: + $ref: '#/definitions/Pool' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Update organization pool with the parameters given. + tags: + - organizations + - pools + /pools: + get: + operationId: ListPools + responses: + "200": + description: Pools + schema: + $ref: '#/definitions/Pools' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: List all pools. + tags: + - pools + /pools/{poolID}: + delete: + operationId: DeletePool + parameters: + - description: ID of the pool to delete. + in: path + name: poolID + required: true + type: string + responses: + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Delete pool by ID. + tags: + - pools + get: + operationId: GetPool + parameters: + - description: ID of the pool to fetch. + in: path + name: poolID + required: true + type: string + responses: + "200": + description: Pool + schema: + $ref: '#/definitions/Pool' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Get pool by ID. + tags: + - pools + put: + operationId: UpdatePool + parameters: + - description: ID of the pool to update. + in: path + name: poolID + required: true + type: string + - description: Parameters to update the pool with. + in: body + name: Body + required: true + schema: + $ref: '#/definitions/UpdatePoolParams' + description: Parameters to update the pool with. + type: object + responses: + "200": + description: Pool + schema: + $ref: '#/definitions/Pool' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: Update pool by ID. + tags: + - pools + /pools/{poolID}/instances: + get: + operationId: ListPoolInstances + parameters: + - description: Runner pool ID. + in: path + name: poolID + required: true + type: string + responses: + "200": + description: Instances + schema: + $ref: '#/definitions/Instances' + default: + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: List runner instances in a pool. + tags: + - instances + /providers: + get: + operationId: ListProviders + responses: + "200": + description: Providers + schema: + $ref: '#/definitions/Providers' + "400": + description: APIErrorResponse + schema: + $ref: '#/definitions/APIErrorResponse' + summary: List all providers. + tags: + - providers /repositories: get: operationId: ListRepos diff --git a/auth/auth.go b/auth/auth.go index a442da70..d912bee6 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -18,11 +18,11 @@ import ( "context" "time" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" + "github.com/cloudbase/garm-provider-common/util" "github.com/cloudbase/garm/config" "github.com/cloudbase/garm/database/common" - runnerErrors "github.com/cloudbase/garm/errors" "github.com/cloudbase/garm/params" - "github.com/cloudbase/garm/util" "github.com/golang-jwt/jwt" "github.com/nbutton23/zxcvbn-go" diff --git a/auth/context.go b/auth/context.go index 694fe26e..27845288 100644 --- a/auth/context.go +++ b/auth/context.go @@ -18,7 +18,6 @@ import ( "context" "github.com/cloudbase/garm/params" - "github.com/cloudbase/garm/runner/providers/common" ) type contextFlags string @@ -65,16 +64,16 @@ func InstanceTokenFetched(ctx context.Context) bool { return elem.(bool) } -func SetInstanceRunnerStatus(ctx context.Context, val common.RunnerStatus) context.Context { +func SetInstanceRunnerStatus(ctx context.Context, val params.RunnerStatus) context.Context { return context.WithValue(ctx, instanceRunnerStatus, val) } -func InstanceRunnerStatus(ctx context.Context) common.RunnerStatus { +func InstanceRunnerStatus(ctx context.Context) params.RunnerStatus { elem := ctx.Value(instanceRunnerStatus) if elem == nil { - return common.RunnerPending + return params.RunnerPending } - return elem.(common.RunnerStatus) + return elem.(params.RunnerStatus) } func SetInstanceName(ctx context.Context, val string) context.Context { diff --git a/auth/instance_middleware.go b/auth/instance_middleware.go index 3af99d6f..01e2e6d0 100644 --- a/auth/instance_middleware.go +++ b/auth/instance_middleware.go @@ -21,12 +21,11 @@ import ( "strings" "time" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/config" dbCommon "github.com/cloudbase/garm/database/common" - runnerErrors "github.com/cloudbase/garm/errors" "github.com/cloudbase/garm/params" "github.com/cloudbase/garm/runner/common" - providerCommon "github.com/cloudbase/garm/runner/providers/common" "github.com/golang-jwt/jwt" "github.com/pkg/errors" @@ -149,7 +148,7 @@ func (amw *instanceMiddleware) Middleware(next http.Handler) http.Handler { } runnerStatus := InstanceRunnerStatus(ctx) - if runnerStatus != providerCommon.RunnerInstalling && runnerStatus != providerCommon.RunnerPending { + if runnerStatus != params.RunnerInstalling && runnerStatus != params.RunnerPending { // Instances that have finished installing can no longer authenticate to the API invalidAuthResponse(w) return diff --git a/auth/jwt.go b/auth/jwt.go index 14dd857d..0b6ca057 100644 --- a/auth/jwt.go +++ b/auth/jwt.go @@ -22,10 +22,10 @@ import ( "net/http" "strings" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" apiParams "github.com/cloudbase/garm/apiserver/params" "github.com/cloudbase/garm/config" dbCommon "github.com/cloudbase/garm/database/common" - runnerErrors "github.com/cloudbase/garm/errors" "github.com/golang-jwt/jwt" ) @@ -74,8 +74,8 @@ func (amw *jwtMiddleware) claimsToContext(ctx context.Context, claims *JWTClaims } func invalidAuthResponse(w http.ResponseWriter) { - w.WriteHeader(http.StatusUnauthorized) w.Header().Add("Content-Type", "application/json") + w.WriteHeader(http.StatusUnauthorized) if err := json.NewEncoder(w).Encode( apiParams.APIErrorResponse{ Error: "Authentication failed", diff --git a/client/credentials/credentials_client.go b/client/credentials/credentials_client.go new file mode 100644 index 00000000..226b702d --- /dev/null +++ b/client/credentials/credentials_client.go @@ -0,0 +1,80 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credentials + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new credentials API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for credentials 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 { + ListCredentials(params *ListCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListCredentialsOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +ListCredentials lists all credentials +*/ +func (a *Client) ListCredentials(params *ListCredentialsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListCredentialsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewListCredentialsParams() + } + op := &runtime.ClientOperation{ + ID: "ListCredentials", + Method: "GET", + PathPattern: "/credentials", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ListCredentialsReader{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.(*ListCredentialsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for ListCredentials: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/client/credentials/list_credentials_parameters.go b/client/credentials/list_credentials_parameters.go new file mode 100644 index 00000000..fdf839d7 --- /dev/null +++ b/client/credentials/list_credentials_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credentials + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewListCredentialsParams creates a new ListCredentialsParams 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 NewListCredentialsParams() *ListCredentialsParams { + return &ListCredentialsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewListCredentialsParamsWithTimeout creates a new ListCredentialsParams object +// with the ability to set a timeout on a request. +func NewListCredentialsParamsWithTimeout(timeout time.Duration) *ListCredentialsParams { + return &ListCredentialsParams{ + timeout: timeout, + } +} + +// NewListCredentialsParamsWithContext creates a new ListCredentialsParams object +// with the ability to set a context for a request. +func NewListCredentialsParamsWithContext(ctx context.Context) *ListCredentialsParams { + return &ListCredentialsParams{ + Context: ctx, + } +} + +// NewListCredentialsParamsWithHTTPClient creates a new ListCredentialsParams object +// with the ability to set a custom HTTPClient for a request. +func NewListCredentialsParamsWithHTTPClient(client *http.Client) *ListCredentialsParams { + return &ListCredentialsParams{ + HTTPClient: client, + } +} + +/* +ListCredentialsParams contains all the parameters to send to the API endpoint + + for the list credentials operation. + + Typically these are written to a http.Request. +*/ +type ListCredentialsParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the list credentials params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListCredentialsParams) WithDefaults() *ListCredentialsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the list credentials params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListCredentialsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the list credentials params +func (o *ListCredentialsParams) WithTimeout(timeout time.Duration) *ListCredentialsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list credentials params +func (o *ListCredentialsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list credentials params +func (o *ListCredentialsParams) WithContext(ctx context.Context) *ListCredentialsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list credentials params +func (o *ListCredentialsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list credentials params +func (o *ListCredentialsParams) WithHTTPClient(client *http.Client) *ListCredentialsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list credentials params +func (o *ListCredentialsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListCredentialsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/credentials/list_credentials_responses.go b/client/credentials/list_credentials_responses.go new file mode 100644 index 00000000..2d4c2f9a --- /dev/null +++ b/client/credentials/list_credentials_responses.go @@ -0,0 +1,174 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credentials + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "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" +) + +// ListCredentialsReader is a Reader for the ListCredentials structure. +type ListCredentialsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListCredentialsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListCredentialsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewListCredentialsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /credentials] ListCredentials", response, response.Code()) + } +} + +// NewListCredentialsOK creates a ListCredentialsOK with default headers values +func NewListCredentialsOK() *ListCredentialsOK { + return &ListCredentialsOK{} +} + +/* +ListCredentialsOK describes a response with status code 200, with default header values. + +Credentials +*/ +type ListCredentialsOK struct { + Payload garm_params.Credentials +} + +// IsSuccess returns true when this list credentials o k response has a 2xx status code +func (o *ListCredentialsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this list credentials o k response has a 3xx status code +func (o *ListCredentialsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list credentials o k response has a 4xx status code +func (o *ListCredentialsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this list credentials o k response has a 5xx status code +func (o *ListCredentialsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this list credentials o k response a status code equal to that given +func (o *ListCredentialsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the list credentials o k response +func (o *ListCredentialsOK) Code() int { + return 200 +} + +func (o *ListCredentialsOK) Error() string { + return fmt.Sprintf("[GET /credentials][%d] listCredentialsOK %+v", 200, o.Payload) +} + +func (o *ListCredentialsOK) String() string { + return fmt.Sprintf("[GET /credentials][%d] listCredentialsOK %+v", 200, o.Payload) +} + +func (o *ListCredentialsOK) GetPayload() garm_params.Credentials { + return o.Payload +} + +func (o *ListCredentialsOK) 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 +} + +// NewListCredentialsBadRequest creates a ListCredentialsBadRequest with default headers values +func NewListCredentialsBadRequest() *ListCredentialsBadRequest { + return &ListCredentialsBadRequest{} +} + +/* +ListCredentialsBadRequest describes a response with status code 400, with default header values. + +APIErrorResponse +*/ +type ListCredentialsBadRequest struct { + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this list credentials bad request response has a 2xx status code +func (o *ListCredentialsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this list credentials bad request response has a 3xx status code +func (o *ListCredentialsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list credentials bad request response has a 4xx status code +func (o *ListCredentialsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this list credentials bad request response has a 5xx status code +func (o *ListCredentialsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this list credentials bad request response a status code equal to that given +func (o *ListCredentialsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the list credentials bad request response +func (o *ListCredentialsBadRequest) Code() int { + return 400 +} + +func (o *ListCredentialsBadRequest) Error() string { + return fmt.Sprintf("[GET /credentials][%d] listCredentialsBadRequest %+v", 400, o.Payload) +} + +func (o *ListCredentialsBadRequest) String() string { + return fmt.Sprintf("[GET /credentials][%d] listCredentialsBadRequest %+v", 400, o.Payload) +} + +func (o *ListCredentialsBadRequest) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *ListCredentialsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/enterprises/create_enterprise_parameters.go b/client/enterprises/create_enterprise_parameters.go new file mode 100644 index 00000000..9b62264a --- /dev/null +++ b/client/enterprises/create_enterprise_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// NewCreateEnterpriseParams creates a new CreateEnterpriseParams 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 NewCreateEnterpriseParams() *CreateEnterpriseParams { + return &CreateEnterpriseParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateEnterpriseParamsWithTimeout creates a new CreateEnterpriseParams object +// with the ability to set a timeout on a request. +func NewCreateEnterpriseParamsWithTimeout(timeout time.Duration) *CreateEnterpriseParams { + return &CreateEnterpriseParams{ + timeout: timeout, + } +} + +// NewCreateEnterpriseParamsWithContext creates a new CreateEnterpriseParams object +// with the ability to set a context for a request. +func NewCreateEnterpriseParamsWithContext(ctx context.Context) *CreateEnterpriseParams { + return &CreateEnterpriseParams{ + Context: ctx, + } +} + +// NewCreateEnterpriseParamsWithHTTPClient creates a new CreateEnterpriseParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateEnterpriseParamsWithHTTPClient(client *http.Client) *CreateEnterpriseParams { + return &CreateEnterpriseParams{ + HTTPClient: client, + } +} + +/* +CreateEnterpriseParams contains all the parameters to send to the API endpoint + + for the create enterprise operation. + + Typically these are written to a http.Request. +*/ +type CreateEnterpriseParams struct { + + /* Body. + + Parameters used to create the enterprise. + */ + Body garm_params.CreateEnterpriseParams + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create enterprise params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateEnterpriseParams) WithDefaults() *CreateEnterpriseParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create enterprise params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateEnterpriseParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create enterprise params +func (o *CreateEnterpriseParams) WithTimeout(timeout time.Duration) *CreateEnterpriseParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create enterprise params +func (o *CreateEnterpriseParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create enterprise params +func (o *CreateEnterpriseParams) WithContext(ctx context.Context) *CreateEnterpriseParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create enterprise params +func (o *CreateEnterpriseParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create enterprise params +func (o *CreateEnterpriseParams) WithHTTPClient(client *http.Client) *CreateEnterpriseParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create enterprise params +func (o *CreateEnterpriseParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create enterprise params +func (o *CreateEnterpriseParams) WithBody(body garm_params.CreateEnterpriseParams) *CreateEnterpriseParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create enterprise params +func (o *CreateEnterpriseParams) SetBody(body garm_params.CreateEnterpriseParams) { + o.Body = body +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateEnterpriseParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/enterprises/create_enterprise_pool_parameters.go b/client/enterprises/create_enterprise_pool_parameters.go new file mode 100644 index 00000000..348d080e --- /dev/null +++ b/client/enterprises/create_enterprise_pool_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// NewCreateEnterprisePoolParams creates a new CreateEnterprisePoolParams 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 NewCreateEnterprisePoolParams() *CreateEnterprisePoolParams { + return &CreateEnterprisePoolParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateEnterprisePoolParamsWithTimeout creates a new CreateEnterprisePoolParams object +// with the ability to set a timeout on a request. +func NewCreateEnterprisePoolParamsWithTimeout(timeout time.Duration) *CreateEnterprisePoolParams { + return &CreateEnterprisePoolParams{ + timeout: timeout, + } +} + +// NewCreateEnterprisePoolParamsWithContext creates a new CreateEnterprisePoolParams object +// with the ability to set a context for a request. +func NewCreateEnterprisePoolParamsWithContext(ctx context.Context) *CreateEnterprisePoolParams { + return &CreateEnterprisePoolParams{ + Context: ctx, + } +} + +// NewCreateEnterprisePoolParamsWithHTTPClient creates a new CreateEnterprisePoolParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateEnterprisePoolParamsWithHTTPClient(client *http.Client) *CreateEnterprisePoolParams { + return &CreateEnterprisePoolParams{ + HTTPClient: client, + } +} + +/* +CreateEnterprisePoolParams contains all the parameters to send to the API endpoint + + for the create enterprise pool operation. + + Typically these are written to a http.Request. +*/ +type CreateEnterprisePoolParams struct { + + /* Body. + + Parameters used when creating the enterprise pool. + */ + Body garm_params.CreatePoolParams + + /* EnterpriseID. + + Enterprise ID. + */ + EnterpriseID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create enterprise pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateEnterprisePoolParams) WithDefaults() *CreateEnterprisePoolParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create enterprise pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateEnterprisePoolParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create enterprise pool params +func (o *CreateEnterprisePoolParams) WithTimeout(timeout time.Duration) *CreateEnterprisePoolParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create enterprise pool params +func (o *CreateEnterprisePoolParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create enterprise pool params +func (o *CreateEnterprisePoolParams) WithContext(ctx context.Context) *CreateEnterprisePoolParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create enterprise pool params +func (o *CreateEnterprisePoolParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create enterprise pool params +func (o *CreateEnterprisePoolParams) WithHTTPClient(client *http.Client) *CreateEnterprisePoolParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create enterprise pool params +func (o *CreateEnterprisePoolParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create enterprise pool params +func (o *CreateEnterprisePoolParams) WithBody(body garm_params.CreatePoolParams) *CreateEnterprisePoolParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create enterprise pool params +func (o *CreateEnterprisePoolParams) SetBody(body garm_params.CreatePoolParams) { + o.Body = body +} + +// WithEnterpriseID adds the enterpriseID to the create enterprise pool params +func (o *CreateEnterprisePoolParams) WithEnterpriseID(enterpriseID string) *CreateEnterprisePoolParams { + o.SetEnterpriseID(enterpriseID) + return o +} + +// SetEnterpriseID adds the enterpriseId to the create enterprise pool params +func (o *CreateEnterprisePoolParams) SetEnterpriseID(enterpriseID string) { + o.EnterpriseID = enterpriseID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateEnterprisePoolParams) 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 enterpriseID + if err := r.SetPathParam("enterpriseID", o.EnterpriseID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/enterprises/create_enterprise_pool_responses.go b/client/enterprises/create_enterprise_pool_responses.go new file mode 100644 index 00000000..55acec14 --- /dev/null +++ b/client/enterprises/create_enterprise_pool_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// CreateEnterprisePoolReader is a Reader for the CreateEnterprisePool structure. +type CreateEnterprisePoolReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateEnterprisePoolReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateEnterprisePoolOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateEnterprisePoolDefault(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 + } +} + +// NewCreateEnterprisePoolOK creates a CreateEnterprisePoolOK with default headers values +func NewCreateEnterprisePoolOK() *CreateEnterprisePoolOK { + return &CreateEnterprisePoolOK{} +} + +/* +CreateEnterprisePoolOK describes a response with status code 200, with default header values. + +Pool +*/ +type CreateEnterprisePoolOK struct { + Payload garm_params.Pool +} + +// IsSuccess returns true when this create enterprise pool o k response has a 2xx status code +func (o *CreateEnterprisePoolOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create enterprise pool o k response has a 3xx status code +func (o *CreateEnterprisePoolOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create enterprise pool o k response has a 4xx status code +func (o *CreateEnterprisePoolOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create enterprise pool o k response has a 5xx status code +func (o *CreateEnterprisePoolOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create enterprise pool o k response a status code equal to that given +func (o *CreateEnterprisePoolOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the create enterprise pool o k response +func (o *CreateEnterprisePoolOK) Code() int { + return 200 +} + +func (o *CreateEnterprisePoolOK) Error() string { + return fmt.Sprintf("[POST /enterprises/{enterpriseID}/pools][%d] createEnterprisePoolOK %+v", 200, o.Payload) +} + +func (o *CreateEnterprisePoolOK) String() string { + return fmt.Sprintf("[POST /enterprises/{enterpriseID}/pools][%d] createEnterprisePoolOK %+v", 200, o.Payload) +} + +func (o *CreateEnterprisePoolOK) GetPayload() garm_params.Pool { + return o.Payload +} + +func (o *CreateEnterprisePoolOK) 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 +} + +// NewCreateEnterprisePoolDefault creates a CreateEnterprisePoolDefault with default headers values +func NewCreateEnterprisePoolDefault(code int) *CreateEnterprisePoolDefault { + return &CreateEnterprisePoolDefault{ + _statusCode: code, + } +} + +/* +CreateEnterprisePoolDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type CreateEnterprisePoolDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this create enterprise pool default response has a 2xx status code +func (o *CreateEnterprisePoolDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create enterprise pool default response has a 3xx status code +func (o *CreateEnterprisePoolDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create enterprise pool default response has a 4xx status code +func (o *CreateEnterprisePoolDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create enterprise pool default response has a 5xx status code +func (o *CreateEnterprisePoolDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create enterprise pool default response a status code equal to that given +func (o *CreateEnterprisePoolDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the create enterprise pool default response +func (o *CreateEnterprisePoolDefault) Code() int { + return o._statusCode +} + +func (o *CreateEnterprisePoolDefault) Error() string { + return fmt.Sprintf("[POST /enterprises/{enterpriseID}/pools][%d] CreateEnterprisePool default %+v", o._statusCode, o.Payload) +} + +func (o *CreateEnterprisePoolDefault) String() string { + return fmt.Sprintf("[POST /enterprises/{enterpriseID}/pools][%d] CreateEnterprisePool default %+v", o._statusCode, o.Payload) +} + +func (o *CreateEnterprisePoolDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *CreateEnterprisePoolDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/enterprises/create_enterprise_responses.go b/client/enterprises/create_enterprise_responses.go new file mode 100644 index 00000000..04a8bdfa --- /dev/null +++ b/client/enterprises/create_enterprise_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// CreateEnterpriseReader is a Reader for the CreateEnterprise structure. +type CreateEnterpriseReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateEnterpriseReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateEnterpriseOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateEnterpriseDefault(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 + } +} + +// NewCreateEnterpriseOK creates a CreateEnterpriseOK with default headers values +func NewCreateEnterpriseOK() *CreateEnterpriseOK { + return &CreateEnterpriseOK{} +} + +/* +CreateEnterpriseOK describes a response with status code 200, with default header values. + +Enterprise +*/ +type CreateEnterpriseOK struct { + Payload garm_params.Enterprise +} + +// IsSuccess returns true when this create enterprise o k response has a 2xx status code +func (o *CreateEnterpriseOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create enterprise o k response has a 3xx status code +func (o *CreateEnterpriseOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create enterprise o k response has a 4xx status code +func (o *CreateEnterpriseOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create enterprise o k response has a 5xx status code +func (o *CreateEnterpriseOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create enterprise o k response a status code equal to that given +func (o *CreateEnterpriseOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the create enterprise o k response +func (o *CreateEnterpriseOK) Code() int { + return 200 +} + +func (o *CreateEnterpriseOK) Error() string { + return fmt.Sprintf("[POST /enterprises][%d] createEnterpriseOK %+v", 200, o.Payload) +} + +func (o *CreateEnterpriseOK) String() string { + return fmt.Sprintf("[POST /enterprises][%d] createEnterpriseOK %+v", 200, o.Payload) +} + +func (o *CreateEnterpriseOK) GetPayload() garm_params.Enterprise { + return o.Payload +} + +func (o *CreateEnterpriseOK) 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 +} + +// NewCreateEnterpriseDefault creates a CreateEnterpriseDefault with default headers values +func NewCreateEnterpriseDefault(code int) *CreateEnterpriseDefault { + return &CreateEnterpriseDefault{ + _statusCode: code, + } +} + +/* +CreateEnterpriseDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type CreateEnterpriseDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this create enterprise default response has a 2xx status code +func (o *CreateEnterpriseDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create enterprise default response has a 3xx status code +func (o *CreateEnterpriseDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create enterprise default response has a 4xx status code +func (o *CreateEnterpriseDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create enterprise default response has a 5xx status code +func (o *CreateEnterpriseDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create enterprise default response a status code equal to that given +func (o *CreateEnterpriseDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the create enterprise default response +func (o *CreateEnterpriseDefault) Code() int { + return o._statusCode +} + +func (o *CreateEnterpriseDefault) Error() string { + return fmt.Sprintf("[POST /enterprises][%d] CreateEnterprise default %+v", o._statusCode, o.Payload) +} + +func (o *CreateEnterpriseDefault) String() string { + return fmt.Sprintf("[POST /enterprises][%d] CreateEnterprise default %+v", o._statusCode, o.Payload) +} + +func (o *CreateEnterpriseDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *CreateEnterpriseDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/enterprises/delete_enterprise_parameters.go b/client/enterprises/delete_enterprise_parameters.go new file mode 100644 index 00000000..5b6b7e5e --- /dev/null +++ b/client/enterprises/delete_enterprise_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// NewDeleteEnterpriseParams creates a new DeleteEnterpriseParams 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 NewDeleteEnterpriseParams() *DeleteEnterpriseParams { + return &DeleteEnterpriseParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteEnterpriseParamsWithTimeout creates a new DeleteEnterpriseParams object +// with the ability to set a timeout on a request. +func NewDeleteEnterpriseParamsWithTimeout(timeout time.Duration) *DeleteEnterpriseParams { + return &DeleteEnterpriseParams{ + timeout: timeout, + } +} + +// NewDeleteEnterpriseParamsWithContext creates a new DeleteEnterpriseParams object +// with the ability to set a context for a request. +func NewDeleteEnterpriseParamsWithContext(ctx context.Context) *DeleteEnterpriseParams { + return &DeleteEnterpriseParams{ + Context: ctx, + } +} + +// NewDeleteEnterpriseParamsWithHTTPClient creates a new DeleteEnterpriseParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteEnterpriseParamsWithHTTPClient(client *http.Client) *DeleteEnterpriseParams { + return &DeleteEnterpriseParams{ + HTTPClient: client, + } +} + +/* +DeleteEnterpriseParams contains all the parameters to send to the API endpoint + + for the delete enterprise operation. + + Typically these are written to a http.Request. +*/ +type DeleteEnterpriseParams struct { + + /* EnterpriseID. + + ID of the enterprise to delete. + */ + EnterpriseID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete enterprise params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteEnterpriseParams) WithDefaults() *DeleteEnterpriseParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete enterprise params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteEnterpriseParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete enterprise params +func (o *DeleteEnterpriseParams) WithTimeout(timeout time.Duration) *DeleteEnterpriseParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete enterprise params +func (o *DeleteEnterpriseParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete enterprise params +func (o *DeleteEnterpriseParams) WithContext(ctx context.Context) *DeleteEnterpriseParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete enterprise params +func (o *DeleteEnterpriseParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete enterprise params +func (o *DeleteEnterpriseParams) WithHTTPClient(client *http.Client) *DeleteEnterpriseParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete enterprise params +func (o *DeleteEnterpriseParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithEnterpriseID adds the enterpriseID to the delete enterprise params +func (o *DeleteEnterpriseParams) WithEnterpriseID(enterpriseID string) *DeleteEnterpriseParams { + o.SetEnterpriseID(enterpriseID) + return o +} + +// SetEnterpriseID adds the enterpriseId to the delete enterprise params +func (o *DeleteEnterpriseParams) SetEnterpriseID(enterpriseID string) { + o.EnterpriseID = enterpriseID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteEnterpriseParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param enterpriseID + if err := r.SetPathParam("enterpriseID", o.EnterpriseID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/enterprises/delete_enterprise_pool_parameters.go b/client/enterprises/delete_enterprise_pool_parameters.go new file mode 100644 index 00000000..bfb7d875 --- /dev/null +++ b/client/enterprises/delete_enterprise_pool_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// NewDeleteEnterprisePoolParams creates a new DeleteEnterprisePoolParams 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 NewDeleteEnterprisePoolParams() *DeleteEnterprisePoolParams { + return &DeleteEnterprisePoolParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteEnterprisePoolParamsWithTimeout creates a new DeleteEnterprisePoolParams object +// with the ability to set a timeout on a request. +func NewDeleteEnterprisePoolParamsWithTimeout(timeout time.Duration) *DeleteEnterprisePoolParams { + return &DeleteEnterprisePoolParams{ + timeout: timeout, + } +} + +// NewDeleteEnterprisePoolParamsWithContext creates a new DeleteEnterprisePoolParams object +// with the ability to set a context for a request. +func NewDeleteEnterprisePoolParamsWithContext(ctx context.Context) *DeleteEnterprisePoolParams { + return &DeleteEnterprisePoolParams{ + Context: ctx, + } +} + +// NewDeleteEnterprisePoolParamsWithHTTPClient creates a new DeleteEnterprisePoolParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteEnterprisePoolParamsWithHTTPClient(client *http.Client) *DeleteEnterprisePoolParams { + return &DeleteEnterprisePoolParams{ + HTTPClient: client, + } +} + +/* +DeleteEnterprisePoolParams contains all the parameters to send to the API endpoint + + for the delete enterprise pool operation. + + Typically these are written to a http.Request. +*/ +type DeleteEnterprisePoolParams struct { + + /* EnterpriseID. + + Enterprise ID. + */ + EnterpriseID string + + /* PoolID. + + ID of the enterprise pool to delete. + */ + PoolID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete enterprise pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteEnterprisePoolParams) WithDefaults() *DeleteEnterprisePoolParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete enterprise pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteEnterprisePoolParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete enterprise pool params +func (o *DeleteEnterprisePoolParams) WithTimeout(timeout time.Duration) *DeleteEnterprisePoolParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete enterprise pool params +func (o *DeleteEnterprisePoolParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete enterprise pool params +func (o *DeleteEnterprisePoolParams) WithContext(ctx context.Context) *DeleteEnterprisePoolParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete enterprise pool params +func (o *DeleteEnterprisePoolParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete enterprise pool params +func (o *DeleteEnterprisePoolParams) WithHTTPClient(client *http.Client) *DeleteEnterprisePoolParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete enterprise pool params +func (o *DeleteEnterprisePoolParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithEnterpriseID adds the enterpriseID to the delete enterprise pool params +func (o *DeleteEnterprisePoolParams) WithEnterpriseID(enterpriseID string) *DeleteEnterprisePoolParams { + o.SetEnterpriseID(enterpriseID) + return o +} + +// SetEnterpriseID adds the enterpriseId to the delete enterprise pool params +func (o *DeleteEnterprisePoolParams) SetEnterpriseID(enterpriseID string) { + o.EnterpriseID = enterpriseID +} + +// WithPoolID adds the poolID to the delete enterprise pool params +func (o *DeleteEnterprisePoolParams) WithPoolID(poolID string) *DeleteEnterprisePoolParams { + o.SetPoolID(poolID) + return o +} + +// SetPoolID adds the poolId to the delete enterprise pool params +func (o *DeleteEnterprisePoolParams) SetPoolID(poolID string) { + o.PoolID = poolID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteEnterprisePoolParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param enterpriseID + if err := r.SetPathParam("enterpriseID", o.EnterpriseID); err != nil { + return err + } + + // path param poolID + if err := r.SetPathParam("poolID", o.PoolID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/enterprises/delete_enterprise_pool_responses.go b/client/enterprises/delete_enterprise_pool_responses.go new file mode 100644 index 00000000..c0348754 --- /dev/null +++ b/client/enterprises/delete_enterprise_pool_responses.go @@ -0,0 +1,103 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// DeleteEnterprisePoolReader is a Reader for the DeleteEnterprisePool structure. +type DeleteEnterprisePoolReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteEnterprisePoolReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + result := NewDeleteEnterprisePoolDefault(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 +} + +// NewDeleteEnterprisePoolDefault creates a DeleteEnterprisePoolDefault with default headers values +func NewDeleteEnterprisePoolDefault(code int) *DeleteEnterprisePoolDefault { + return &DeleteEnterprisePoolDefault{ + _statusCode: code, + } +} + +/* +DeleteEnterprisePoolDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type DeleteEnterprisePoolDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this delete enterprise pool default response has a 2xx status code +func (o *DeleteEnterprisePoolDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete enterprise pool default response has a 3xx status code +func (o *DeleteEnterprisePoolDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete enterprise pool default response has a 4xx status code +func (o *DeleteEnterprisePoolDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete enterprise pool default response has a 5xx status code +func (o *DeleteEnterprisePoolDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete enterprise pool default response a status code equal to that given +func (o *DeleteEnterprisePoolDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the delete enterprise pool default response +func (o *DeleteEnterprisePoolDefault) Code() int { + return o._statusCode +} + +func (o *DeleteEnterprisePoolDefault) Error() string { + return fmt.Sprintf("[DELETE /enterprises/{enterpriseID}/pools/{poolID}][%d] DeleteEnterprisePool default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteEnterprisePoolDefault) String() string { + return fmt.Sprintf("[DELETE /enterprises/{enterpriseID}/pools/{poolID}][%d] DeleteEnterprisePool default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteEnterprisePoolDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *DeleteEnterprisePoolDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/enterprises/delete_enterprise_responses.go b/client/enterprises/delete_enterprise_responses.go new file mode 100644 index 00000000..f846cdd0 --- /dev/null +++ b/client/enterprises/delete_enterprise_responses.go @@ -0,0 +1,103 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// DeleteEnterpriseReader is a Reader for the DeleteEnterprise structure. +type DeleteEnterpriseReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteEnterpriseReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + result := NewDeleteEnterpriseDefault(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 +} + +// NewDeleteEnterpriseDefault creates a DeleteEnterpriseDefault with default headers values +func NewDeleteEnterpriseDefault(code int) *DeleteEnterpriseDefault { + return &DeleteEnterpriseDefault{ + _statusCode: code, + } +} + +/* +DeleteEnterpriseDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type DeleteEnterpriseDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this delete enterprise default response has a 2xx status code +func (o *DeleteEnterpriseDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete enterprise default response has a 3xx status code +func (o *DeleteEnterpriseDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete enterprise default response has a 4xx status code +func (o *DeleteEnterpriseDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete enterprise default response has a 5xx status code +func (o *DeleteEnterpriseDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete enterprise default response a status code equal to that given +func (o *DeleteEnterpriseDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the delete enterprise default response +func (o *DeleteEnterpriseDefault) Code() int { + return o._statusCode +} + +func (o *DeleteEnterpriseDefault) Error() string { + return fmt.Sprintf("[DELETE /enterprises/{enterpriseID}][%d] DeleteEnterprise default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteEnterpriseDefault) String() string { + return fmt.Sprintf("[DELETE /enterprises/{enterpriseID}][%d] DeleteEnterprise default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteEnterpriseDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *DeleteEnterpriseDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/enterprises/enterprises_client.go b/client/enterprises/enterprises_client.go new file mode 100644 index 00000000..a0029c06 --- /dev/null +++ b/client/enterprises/enterprises_client.go @@ -0,0 +1,465 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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 enterprises API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for enterprises 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 { + CreateEnterprise(params *CreateEnterpriseParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateEnterpriseOK, error) + + CreateEnterprisePool(params *CreateEnterprisePoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateEnterprisePoolOK, error) + + DeleteEnterprise(params *DeleteEnterpriseParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error + + DeleteEnterprisePool(params *DeleteEnterprisePoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error + + GetEnterprise(params *GetEnterpriseParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetEnterpriseOK, error) + + GetEnterprisePool(params *GetEnterprisePoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetEnterprisePoolOK, error) + + ListEnterpriseInstances(params *ListEnterpriseInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListEnterpriseInstancesOK, error) + + ListEnterprisePools(params *ListEnterprisePoolsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListEnterprisePoolsOK, error) + + ListEnterprises(params *ListEnterprisesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListEnterprisesOK, error) + + UpdateEnterprise(params *UpdateEnterpriseParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateEnterpriseOK, error) + + UpdateEnterprisePool(params *UpdateEnterprisePoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateEnterprisePoolOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +CreateEnterprise creates enterprise with the given parameters +*/ +func (a *Client) CreateEnterprise(params *CreateEnterpriseParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateEnterpriseOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateEnterpriseParams() + } + op := &runtime.ClientOperation{ + ID: "CreateEnterprise", + Method: "POST", + PathPattern: "/enterprises", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateEnterpriseReader{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.(*CreateEnterpriseOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateEnterpriseDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* +CreateEnterprisePool creates enterprise pool with the parameters given +*/ +func (a *Client) CreateEnterprisePool(params *CreateEnterprisePoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateEnterprisePoolOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateEnterprisePoolParams() + } + op := &runtime.ClientOperation{ + ID: "CreateEnterprisePool", + Method: "POST", + PathPattern: "/enterprises/{enterpriseID}/pools", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateEnterprisePoolReader{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.(*CreateEnterprisePoolOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateEnterprisePoolDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* +DeleteEnterprise deletes enterprise by ID +*/ +func (a *Client) DeleteEnterprise(params *DeleteEnterpriseParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteEnterpriseParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteEnterprise", + Method: "DELETE", + PathPattern: "/enterprises/{enterpriseID}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteEnterpriseReader{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 +} + +/* +DeleteEnterprisePool deletes enterprise pool by ID +*/ +func (a *Client) DeleteEnterprisePool(params *DeleteEnterprisePoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteEnterprisePoolParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteEnterprisePool", + Method: "DELETE", + PathPattern: "/enterprises/{enterpriseID}/pools/{poolID}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteEnterprisePoolReader{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 +} + +/* +GetEnterprise gets enterprise by ID +*/ +func (a *Client) GetEnterprise(params *GetEnterpriseParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetEnterpriseOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetEnterpriseParams() + } + op := &runtime.ClientOperation{ + ID: "GetEnterprise", + Method: "GET", + PathPattern: "/enterprises/{enterpriseID}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetEnterpriseReader{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.(*GetEnterpriseOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetEnterpriseDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* +GetEnterprisePool gets enterprise pool by ID +*/ +func (a *Client) GetEnterprisePool(params *GetEnterprisePoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetEnterprisePoolOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetEnterprisePoolParams() + } + op := &runtime.ClientOperation{ + ID: "GetEnterprisePool", + Method: "GET", + PathPattern: "/enterprises/{enterpriseID}/pools/{poolID}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetEnterprisePoolReader{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.(*GetEnterprisePoolOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetEnterprisePoolDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* +ListEnterpriseInstances lists enterprise instances +*/ +func (a *Client) ListEnterpriseInstances(params *ListEnterpriseInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListEnterpriseInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewListEnterpriseInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "ListEnterpriseInstances", + Method: "GET", + PathPattern: "/enterprises/{enterpriseID}/instances", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ListEnterpriseInstancesReader{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.(*ListEnterpriseInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ListEnterpriseInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* +ListEnterprisePools lists enterprise pools +*/ +func (a *Client) ListEnterprisePools(params *ListEnterprisePoolsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListEnterprisePoolsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewListEnterprisePoolsParams() + } + op := &runtime.ClientOperation{ + ID: "ListEnterprisePools", + Method: "GET", + PathPattern: "/enterprises/{enterpriseID}/pools", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ListEnterprisePoolsReader{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.(*ListEnterprisePoolsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ListEnterprisePoolsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* +ListEnterprises lists all enterprises +*/ +func (a *Client) ListEnterprises(params *ListEnterprisesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListEnterprisesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewListEnterprisesParams() + } + op := &runtime.ClientOperation{ + ID: "ListEnterprises", + Method: "GET", + PathPattern: "/enterprises", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ListEnterprisesReader{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.(*ListEnterprisesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ListEnterprisesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* +UpdateEnterprise updates enterprise with the given parameters +*/ +func (a *Client) UpdateEnterprise(params *UpdateEnterpriseParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateEnterpriseOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewUpdateEnterpriseParams() + } + op := &runtime.ClientOperation{ + ID: "UpdateEnterprise", + Method: "PUT", + PathPattern: "/enterprises/{enterpriseID}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &UpdateEnterpriseReader{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.(*UpdateEnterpriseOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*UpdateEnterpriseDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* +UpdateEnterprisePool updates enterprise pool with the parameters given +*/ +func (a *Client) UpdateEnterprisePool(params *UpdateEnterprisePoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateEnterprisePoolOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewUpdateEnterprisePoolParams() + } + op := &runtime.ClientOperation{ + ID: "UpdateEnterprisePool", + Method: "PUT", + PathPattern: "/enterprises/{enterpriseID}/pools/{poolID}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &UpdateEnterprisePoolReader{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.(*UpdateEnterprisePoolOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*UpdateEnterprisePoolDefault) + 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 +} diff --git a/client/enterprises/get_enterprise_parameters.go b/client/enterprises/get_enterprise_parameters.go new file mode 100644 index 00000000..97161943 --- /dev/null +++ b/client/enterprises/get_enterprise_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// NewGetEnterpriseParams creates a new GetEnterpriseParams 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 NewGetEnterpriseParams() *GetEnterpriseParams { + return &GetEnterpriseParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetEnterpriseParamsWithTimeout creates a new GetEnterpriseParams object +// with the ability to set a timeout on a request. +func NewGetEnterpriseParamsWithTimeout(timeout time.Duration) *GetEnterpriseParams { + return &GetEnterpriseParams{ + timeout: timeout, + } +} + +// NewGetEnterpriseParamsWithContext creates a new GetEnterpriseParams object +// with the ability to set a context for a request. +func NewGetEnterpriseParamsWithContext(ctx context.Context) *GetEnterpriseParams { + return &GetEnterpriseParams{ + Context: ctx, + } +} + +// NewGetEnterpriseParamsWithHTTPClient creates a new GetEnterpriseParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetEnterpriseParamsWithHTTPClient(client *http.Client) *GetEnterpriseParams { + return &GetEnterpriseParams{ + HTTPClient: client, + } +} + +/* +GetEnterpriseParams contains all the parameters to send to the API endpoint + + for the get enterprise operation. + + Typically these are written to a http.Request. +*/ +type GetEnterpriseParams struct { + + /* EnterpriseID. + + The ID of the enterprise to fetch. + */ + EnterpriseID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get enterprise params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetEnterpriseParams) WithDefaults() *GetEnterpriseParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get enterprise params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetEnterpriseParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get enterprise params +func (o *GetEnterpriseParams) WithTimeout(timeout time.Duration) *GetEnterpriseParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get enterprise params +func (o *GetEnterpriseParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get enterprise params +func (o *GetEnterpriseParams) WithContext(ctx context.Context) *GetEnterpriseParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get enterprise params +func (o *GetEnterpriseParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get enterprise params +func (o *GetEnterpriseParams) WithHTTPClient(client *http.Client) *GetEnterpriseParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get enterprise params +func (o *GetEnterpriseParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithEnterpriseID adds the enterpriseID to the get enterprise params +func (o *GetEnterpriseParams) WithEnterpriseID(enterpriseID string) *GetEnterpriseParams { + o.SetEnterpriseID(enterpriseID) + return o +} + +// SetEnterpriseID adds the enterpriseId to the get enterprise params +func (o *GetEnterpriseParams) SetEnterpriseID(enterpriseID string) { + o.EnterpriseID = enterpriseID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetEnterpriseParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param enterpriseID + if err := r.SetPathParam("enterpriseID", o.EnterpriseID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/enterprises/get_enterprise_pool_parameters.go b/client/enterprises/get_enterprise_pool_parameters.go new file mode 100644 index 00000000..3d8180e6 --- /dev/null +++ b/client/enterprises/get_enterprise_pool_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// NewGetEnterprisePoolParams creates a new GetEnterprisePoolParams 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 NewGetEnterprisePoolParams() *GetEnterprisePoolParams { + return &GetEnterprisePoolParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetEnterprisePoolParamsWithTimeout creates a new GetEnterprisePoolParams object +// with the ability to set a timeout on a request. +func NewGetEnterprisePoolParamsWithTimeout(timeout time.Duration) *GetEnterprisePoolParams { + return &GetEnterprisePoolParams{ + timeout: timeout, + } +} + +// NewGetEnterprisePoolParamsWithContext creates a new GetEnterprisePoolParams object +// with the ability to set a context for a request. +func NewGetEnterprisePoolParamsWithContext(ctx context.Context) *GetEnterprisePoolParams { + return &GetEnterprisePoolParams{ + Context: ctx, + } +} + +// NewGetEnterprisePoolParamsWithHTTPClient creates a new GetEnterprisePoolParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetEnterprisePoolParamsWithHTTPClient(client *http.Client) *GetEnterprisePoolParams { + return &GetEnterprisePoolParams{ + HTTPClient: client, + } +} + +/* +GetEnterprisePoolParams contains all the parameters to send to the API endpoint + + for the get enterprise pool operation. + + Typically these are written to a http.Request. +*/ +type GetEnterprisePoolParams struct { + + /* EnterpriseID. + + Enterprise ID. + */ + EnterpriseID string + + /* PoolID. + + Pool ID. + */ + PoolID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get enterprise pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetEnterprisePoolParams) WithDefaults() *GetEnterprisePoolParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get enterprise pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetEnterprisePoolParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get enterprise pool params +func (o *GetEnterprisePoolParams) WithTimeout(timeout time.Duration) *GetEnterprisePoolParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get enterprise pool params +func (o *GetEnterprisePoolParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get enterprise pool params +func (o *GetEnterprisePoolParams) WithContext(ctx context.Context) *GetEnterprisePoolParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get enterprise pool params +func (o *GetEnterprisePoolParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get enterprise pool params +func (o *GetEnterprisePoolParams) WithHTTPClient(client *http.Client) *GetEnterprisePoolParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get enterprise pool params +func (o *GetEnterprisePoolParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithEnterpriseID adds the enterpriseID to the get enterprise pool params +func (o *GetEnterprisePoolParams) WithEnterpriseID(enterpriseID string) *GetEnterprisePoolParams { + o.SetEnterpriseID(enterpriseID) + return o +} + +// SetEnterpriseID adds the enterpriseId to the get enterprise pool params +func (o *GetEnterprisePoolParams) SetEnterpriseID(enterpriseID string) { + o.EnterpriseID = enterpriseID +} + +// WithPoolID adds the poolID to the get enterprise pool params +func (o *GetEnterprisePoolParams) WithPoolID(poolID string) *GetEnterprisePoolParams { + o.SetPoolID(poolID) + return o +} + +// SetPoolID adds the poolId to the get enterprise pool params +func (o *GetEnterprisePoolParams) SetPoolID(poolID string) { + o.PoolID = poolID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetEnterprisePoolParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param enterpriseID + if err := r.SetPathParam("enterpriseID", o.EnterpriseID); err != nil { + return err + } + + // path param poolID + if err := r.SetPathParam("poolID", o.PoolID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/enterprises/get_enterprise_pool_responses.go b/client/enterprises/get_enterprise_pool_responses.go new file mode 100644 index 00000000..da0f54ad --- /dev/null +++ b/client/enterprises/get_enterprise_pool_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// GetEnterprisePoolReader is a Reader for the GetEnterprisePool structure. +type GetEnterprisePoolReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetEnterprisePoolReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetEnterprisePoolOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetEnterprisePoolDefault(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 + } +} + +// NewGetEnterprisePoolOK creates a GetEnterprisePoolOK with default headers values +func NewGetEnterprisePoolOK() *GetEnterprisePoolOK { + return &GetEnterprisePoolOK{} +} + +/* +GetEnterprisePoolOK describes a response with status code 200, with default header values. + +Pool +*/ +type GetEnterprisePoolOK struct { + Payload garm_params.Pool +} + +// IsSuccess returns true when this get enterprise pool o k response has a 2xx status code +func (o *GetEnterprisePoolOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get enterprise pool o k response has a 3xx status code +func (o *GetEnterprisePoolOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get enterprise pool o k response has a 4xx status code +func (o *GetEnterprisePoolOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get enterprise pool o k response has a 5xx status code +func (o *GetEnterprisePoolOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get enterprise pool o k response a status code equal to that given +func (o *GetEnterprisePoolOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get enterprise pool o k response +func (o *GetEnterprisePoolOK) Code() int { + return 200 +} + +func (o *GetEnterprisePoolOK) Error() string { + return fmt.Sprintf("[GET /enterprises/{enterpriseID}/pools/{poolID}][%d] getEnterprisePoolOK %+v", 200, o.Payload) +} + +func (o *GetEnterprisePoolOK) String() string { + return fmt.Sprintf("[GET /enterprises/{enterpriseID}/pools/{poolID}][%d] getEnterprisePoolOK %+v", 200, o.Payload) +} + +func (o *GetEnterprisePoolOK) GetPayload() garm_params.Pool { + return o.Payload +} + +func (o *GetEnterprisePoolOK) 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 +} + +// NewGetEnterprisePoolDefault creates a GetEnterprisePoolDefault with default headers values +func NewGetEnterprisePoolDefault(code int) *GetEnterprisePoolDefault { + return &GetEnterprisePoolDefault{ + _statusCode: code, + } +} + +/* +GetEnterprisePoolDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type GetEnterprisePoolDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this get enterprise pool default response has a 2xx status code +func (o *GetEnterprisePoolDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get enterprise pool default response has a 3xx status code +func (o *GetEnterprisePoolDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get enterprise pool default response has a 4xx status code +func (o *GetEnterprisePoolDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get enterprise pool default response has a 5xx status code +func (o *GetEnterprisePoolDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get enterprise pool default response a status code equal to that given +func (o *GetEnterprisePoolDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the get enterprise pool default response +func (o *GetEnterprisePoolDefault) Code() int { + return o._statusCode +} + +func (o *GetEnterprisePoolDefault) Error() string { + return fmt.Sprintf("[GET /enterprises/{enterpriseID}/pools/{poolID}][%d] GetEnterprisePool default %+v", o._statusCode, o.Payload) +} + +func (o *GetEnterprisePoolDefault) String() string { + return fmt.Sprintf("[GET /enterprises/{enterpriseID}/pools/{poolID}][%d] GetEnterprisePool default %+v", o._statusCode, o.Payload) +} + +func (o *GetEnterprisePoolDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *GetEnterprisePoolDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/enterprises/get_enterprise_responses.go b/client/enterprises/get_enterprise_responses.go new file mode 100644 index 00000000..896393bd --- /dev/null +++ b/client/enterprises/get_enterprise_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// GetEnterpriseReader is a Reader for the GetEnterprise structure. +type GetEnterpriseReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetEnterpriseReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetEnterpriseOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetEnterpriseDefault(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 + } +} + +// NewGetEnterpriseOK creates a GetEnterpriseOK with default headers values +func NewGetEnterpriseOK() *GetEnterpriseOK { + return &GetEnterpriseOK{} +} + +/* +GetEnterpriseOK describes a response with status code 200, with default header values. + +Enterprise +*/ +type GetEnterpriseOK struct { + Payload garm_params.Enterprise +} + +// IsSuccess returns true when this get enterprise o k response has a 2xx status code +func (o *GetEnterpriseOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get enterprise o k response has a 3xx status code +func (o *GetEnterpriseOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get enterprise o k response has a 4xx status code +func (o *GetEnterpriseOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get enterprise o k response has a 5xx status code +func (o *GetEnterpriseOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get enterprise o k response a status code equal to that given +func (o *GetEnterpriseOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get enterprise o k response +func (o *GetEnterpriseOK) Code() int { + return 200 +} + +func (o *GetEnterpriseOK) Error() string { + return fmt.Sprintf("[GET /enterprises/{enterpriseID}][%d] getEnterpriseOK %+v", 200, o.Payload) +} + +func (o *GetEnterpriseOK) String() string { + return fmt.Sprintf("[GET /enterprises/{enterpriseID}][%d] getEnterpriseOK %+v", 200, o.Payload) +} + +func (o *GetEnterpriseOK) GetPayload() garm_params.Enterprise { + return o.Payload +} + +func (o *GetEnterpriseOK) 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 +} + +// NewGetEnterpriseDefault creates a GetEnterpriseDefault with default headers values +func NewGetEnterpriseDefault(code int) *GetEnterpriseDefault { + return &GetEnterpriseDefault{ + _statusCode: code, + } +} + +/* +GetEnterpriseDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type GetEnterpriseDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this get enterprise default response has a 2xx status code +func (o *GetEnterpriseDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get enterprise default response has a 3xx status code +func (o *GetEnterpriseDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get enterprise default response has a 4xx status code +func (o *GetEnterpriseDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get enterprise default response has a 5xx status code +func (o *GetEnterpriseDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get enterprise default response a status code equal to that given +func (o *GetEnterpriseDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the get enterprise default response +func (o *GetEnterpriseDefault) Code() int { + return o._statusCode +} + +func (o *GetEnterpriseDefault) Error() string { + return fmt.Sprintf("[GET /enterprises/{enterpriseID}][%d] GetEnterprise default %+v", o._statusCode, o.Payload) +} + +func (o *GetEnterpriseDefault) String() string { + return fmt.Sprintf("[GET /enterprises/{enterpriseID}][%d] GetEnterprise default %+v", o._statusCode, o.Payload) +} + +func (o *GetEnterpriseDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *GetEnterpriseDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/enterprises/list_enterprise_instances_parameters.go b/client/enterprises/list_enterprise_instances_parameters.go new file mode 100644 index 00000000..5e23c3e0 --- /dev/null +++ b/client/enterprises/list_enterprise_instances_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// NewListEnterpriseInstancesParams creates a new ListEnterpriseInstancesParams 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 NewListEnterpriseInstancesParams() *ListEnterpriseInstancesParams { + return &ListEnterpriseInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewListEnterpriseInstancesParamsWithTimeout creates a new ListEnterpriseInstancesParams object +// with the ability to set a timeout on a request. +func NewListEnterpriseInstancesParamsWithTimeout(timeout time.Duration) *ListEnterpriseInstancesParams { + return &ListEnterpriseInstancesParams{ + timeout: timeout, + } +} + +// NewListEnterpriseInstancesParamsWithContext creates a new ListEnterpriseInstancesParams object +// with the ability to set a context for a request. +func NewListEnterpriseInstancesParamsWithContext(ctx context.Context) *ListEnterpriseInstancesParams { + return &ListEnterpriseInstancesParams{ + Context: ctx, + } +} + +// NewListEnterpriseInstancesParamsWithHTTPClient creates a new ListEnterpriseInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewListEnterpriseInstancesParamsWithHTTPClient(client *http.Client) *ListEnterpriseInstancesParams { + return &ListEnterpriseInstancesParams{ + HTTPClient: client, + } +} + +/* +ListEnterpriseInstancesParams contains all the parameters to send to the API endpoint + + for the list enterprise instances operation. + + Typically these are written to a http.Request. +*/ +type ListEnterpriseInstancesParams struct { + + /* EnterpriseID. + + Enterprise ID. + */ + EnterpriseID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the list enterprise instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListEnterpriseInstancesParams) WithDefaults() *ListEnterpriseInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the list enterprise instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListEnterpriseInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the list enterprise instances params +func (o *ListEnterpriseInstancesParams) WithTimeout(timeout time.Duration) *ListEnterpriseInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list enterprise instances params +func (o *ListEnterpriseInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list enterprise instances params +func (o *ListEnterpriseInstancesParams) WithContext(ctx context.Context) *ListEnterpriseInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list enterprise instances params +func (o *ListEnterpriseInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list enterprise instances params +func (o *ListEnterpriseInstancesParams) WithHTTPClient(client *http.Client) *ListEnterpriseInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list enterprise instances params +func (o *ListEnterpriseInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithEnterpriseID adds the enterpriseID to the list enterprise instances params +func (o *ListEnterpriseInstancesParams) WithEnterpriseID(enterpriseID string) *ListEnterpriseInstancesParams { + o.SetEnterpriseID(enterpriseID) + return o +} + +// SetEnterpriseID adds the enterpriseId to the list enterprise instances params +func (o *ListEnterpriseInstancesParams) SetEnterpriseID(enterpriseID string) { + o.EnterpriseID = enterpriseID +} + +// WriteToRequest writes these params to a swagger request +func (o *ListEnterpriseInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param enterpriseID + if err := r.SetPathParam("enterpriseID", o.EnterpriseID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/enterprises/list_enterprise_instances_responses.go b/client/enterprises/list_enterprise_instances_responses.go new file mode 100644 index 00000000..bf28ccda --- /dev/null +++ b/client/enterprises/list_enterprise_instances_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// ListEnterpriseInstancesReader is a Reader for the ListEnterpriseInstances structure. +type ListEnterpriseInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListEnterpriseInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListEnterpriseInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewListEnterpriseInstancesDefault(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 + } +} + +// NewListEnterpriseInstancesOK creates a ListEnterpriseInstancesOK with default headers values +func NewListEnterpriseInstancesOK() *ListEnterpriseInstancesOK { + return &ListEnterpriseInstancesOK{} +} + +/* +ListEnterpriseInstancesOK describes a response with status code 200, with default header values. + +Instances +*/ +type ListEnterpriseInstancesOK struct { + Payload garm_params.Instances +} + +// IsSuccess returns true when this list enterprise instances o k response has a 2xx status code +func (o *ListEnterpriseInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this list enterprise instances o k response has a 3xx status code +func (o *ListEnterpriseInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list enterprise instances o k response has a 4xx status code +func (o *ListEnterpriseInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this list enterprise instances o k response has a 5xx status code +func (o *ListEnterpriseInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this list enterprise instances o k response a status code equal to that given +func (o *ListEnterpriseInstancesOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the list enterprise instances o k response +func (o *ListEnterpriseInstancesOK) Code() int { + return 200 +} + +func (o *ListEnterpriseInstancesOK) Error() string { + return fmt.Sprintf("[GET /enterprises/{enterpriseID}/instances][%d] listEnterpriseInstancesOK %+v", 200, o.Payload) +} + +func (o *ListEnterpriseInstancesOK) String() string { + return fmt.Sprintf("[GET /enterprises/{enterpriseID}/instances][%d] listEnterpriseInstancesOK %+v", 200, o.Payload) +} + +func (o *ListEnterpriseInstancesOK) GetPayload() garm_params.Instances { + return o.Payload +} + +func (o *ListEnterpriseInstancesOK) 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 +} + +// NewListEnterpriseInstancesDefault creates a ListEnterpriseInstancesDefault with default headers values +func NewListEnterpriseInstancesDefault(code int) *ListEnterpriseInstancesDefault { + return &ListEnterpriseInstancesDefault{ + _statusCode: code, + } +} + +/* +ListEnterpriseInstancesDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type ListEnterpriseInstancesDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this list enterprise instances default response has a 2xx status code +func (o *ListEnterpriseInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this list enterprise instances default response has a 3xx status code +func (o *ListEnterpriseInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this list enterprise instances default response has a 4xx status code +func (o *ListEnterpriseInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this list enterprise instances default response has a 5xx status code +func (o *ListEnterpriseInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this list enterprise instances default response a status code equal to that given +func (o *ListEnterpriseInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the list enterprise instances default response +func (o *ListEnterpriseInstancesDefault) Code() int { + return o._statusCode +} + +func (o *ListEnterpriseInstancesDefault) Error() string { + return fmt.Sprintf("[GET /enterprises/{enterpriseID}/instances][%d] ListEnterpriseInstances default %+v", o._statusCode, o.Payload) +} + +func (o *ListEnterpriseInstancesDefault) String() string { + return fmt.Sprintf("[GET /enterprises/{enterpriseID}/instances][%d] ListEnterpriseInstances default %+v", o._statusCode, o.Payload) +} + +func (o *ListEnterpriseInstancesDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *ListEnterpriseInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/enterprises/list_enterprise_pools_parameters.go b/client/enterprises/list_enterprise_pools_parameters.go new file mode 100644 index 00000000..6c58fe0e --- /dev/null +++ b/client/enterprises/list_enterprise_pools_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// NewListEnterprisePoolsParams creates a new ListEnterprisePoolsParams 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 NewListEnterprisePoolsParams() *ListEnterprisePoolsParams { + return &ListEnterprisePoolsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewListEnterprisePoolsParamsWithTimeout creates a new ListEnterprisePoolsParams object +// with the ability to set a timeout on a request. +func NewListEnterprisePoolsParamsWithTimeout(timeout time.Duration) *ListEnterprisePoolsParams { + return &ListEnterprisePoolsParams{ + timeout: timeout, + } +} + +// NewListEnterprisePoolsParamsWithContext creates a new ListEnterprisePoolsParams object +// with the ability to set a context for a request. +func NewListEnterprisePoolsParamsWithContext(ctx context.Context) *ListEnterprisePoolsParams { + return &ListEnterprisePoolsParams{ + Context: ctx, + } +} + +// NewListEnterprisePoolsParamsWithHTTPClient creates a new ListEnterprisePoolsParams object +// with the ability to set a custom HTTPClient for a request. +func NewListEnterprisePoolsParamsWithHTTPClient(client *http.Client) *ListEnterprisePoolsParams { + return &ListEnterprisePoolsParams{ + HTTPClient: client, + } +} + +/* +ListEnterprisePoolsParams contains all the parameters to send to the API endpoint + + for the list enterprise pools operation. + + Typically these are written to a http.Request. +*/ +type ListEnterprisePoolsParams struct { + + /* EnterpriseID. + + Enterprise ID. + */ + EnterpriseID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the list enterprise pools params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListEnterprisePoolsParams) WithDefaults() *ListEnterprisePoolsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the list enterprise pools params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListEnterprisePoolsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the list enterprise pools params +func (o *ListEnterprisePoolsParams) WithTimeout(timeout time.Duration) *ListEnterprisePoolsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list enterprise pools params +func (o *ListEnterprisePoolsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list enterprise pools params +func (o *ListEnterprisePoolsParams) WithContext(ctx context.Context) *ListEnterprisePoolsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list enterprise pools params +func (o *ListEnterprisePoolsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list enterprise pools params +func (o *ListEnterprisePoolsParams) WithHTTPClient(client *http.Client) *ListEnterprisePoolsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list enterprise pools params +func (o *ListEnterprisePoolsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithEnterpriseID adds the enterpriseID to the list enterprise pools params +func (o *ListEnterprisePoolsParams) WithEnterpriseID(enterpriseID string) *ListEnterprisePoolsParams { + o.SetEnterpriseID(enterpriseID) + return o +} + +// SetEnterpriseID adds the enterpriseId to the list enterprise pools params +func (o *ListEnterprisePoolsParams) SetEnterpriseID(enterpriseID string) { + o.EnterpriseID = enterpriseID +} + +// WriteToRequest writes these params to a swagger request +func (o *ListEnterprisePoolsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param enterpriseID + if err := r.SetPathParam("enterpriseID", o.EnterpriseID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/enterprises/list_enterprise_pools_responses.go b/client/enterprises/list_enterprise_pools_responses.go new file mode 100644 index 00000000..3c228155 --- /dev/null +++ b/client/enterprises/list_enterprise_pools_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// ListEnterprisePoolsReader is a Reader for the ListEnterprisePools structure. +type ListEnterprisePoolsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListEnterprisePoolsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListEnterprisePoolsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewListEnterprisePoolsDefault(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 + } +} + +// NewListEnterprisePoolsOK creates a ListEnterprisePoolsOK with default headers values +func NewListEnterprisePoolsOK() *ListEnterprisePoolsOK { + return &ListEnterprisePoolsOK{} +} + +/* +ListEnterprisePoolsOK describes a response with status code 200, with default header values. + +Pools +*/ +type ListEnterprisePoolsOK struct { + Payload garm_params.Pools +} + +// IsSuccess returns true when this list enterprise pools o k response has a 2xx status code +func (o *ListEnterprisePoolsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this list enterprise pools o k response has a 3xx status code +func (o *ListEnterprisePoolsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list enterprise pools o k response has a 4xx status code +func (o *ListEnterprisePoolsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this list enterprise pools o k response has a 5xx status code +func (o *ListEnterprisePoolsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this list enterprise pools o k response a status code equal to that given +func (o *ListEnterprisePoolsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the list enterprise pools o k response +func (o *ListEnterprisePoolsOK) Code() int { + return 200 +} + +func (o *ListEnterprisePoolsOK) Error() string { + return fmt.Sprintf("[GET /enterprises/{enterpriseID}/pools][%d] listEnterprisePoolsOK %+v", 200, o.Payload) +} + +func (o *ListEnterprisePoolsOK) String() string { + return fmt.Sprintf("[GET /enterprises/{enterpriseID}/pools][%d] listEnterprisePoolsOK %+v", 200, o.Payload) +} + +func (o *ListEnterprisePoolsOK) GetPayload() garm_params.Pools { + return o.Payload +} + +func (o *ListEnterprisePoolsOK) 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 +} + +// NewListEnterprisePoolsDefault creates a ListEnterprisePoolsDefault with default headers values +func NewListEnterprisePoolsDefault(code int) *ListEnterprisePoolsDefault { + return &ListEnterprisePoolsDefault{ + _statusCode: code, + } +} + +/* +ListEnterprisePoolsDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type ListEnterprisePoolsDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this list enterprise pools default response has a 2xx status code +func (o *ListEnterprisePoolsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this list enterprise pools default response has a 3xx status code +func (o *ListEnterprisePoolsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this list enterprise pools default response has a 4xx status code +func (o *ListEnterprisePoolsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this list enterprise pools default response has a 5xx status code +func (o *ListEnterprisePoolsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this list enterprise pools default response a status code equal to that given +func (o *ListEnterprisePoolsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the list enterprise pools default response +func (o *ListEnterprisePoolsDefault) Code() int { + return o._statusCode +} + +func (o *ListEnterprisePoolsDefault) Error() string { + return fmt.Sprintf("[GET /enterprises/{enterpriseID}/pools][%d] ListEnterprisePools default %+v", o._statusCode, o.Payload) +} + +func (o *ListEnterprisePoolsDefault) String() string { + return fmt.Sprintf("[GET /enterprises/{enterpriseID}/pools][%d] ListEnterprisePools default %+v", o._statusCode, o.Payload) +} + +func (o *ListEnterprisePoolsDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *ListEnterprisePoolsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/enterprises/list_enterprises_parameters.go b/client/enterprises/list_enterprises_parameters.go new file mode 100644 index 00000000..83291c5f --- /dev/null +++ b/client/enterprises/list_enterprises_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// NewListEnterprisesParams creates a new ListEnterprisesParams 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 NewListEnterprisesParams() *ListEnterprisesParams { + return &ListEnterprisesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewListEnterprisesParamsWithTimeout creates a new ListEnterprisesParams object +// with the ability to set a timeout on a request. +func NewListEnterprisesParamsWithTimeout(timeout time.Duration) *ListEnterprisesParams { + return &ListEnterprisesParams{ + timeout: timeout, + } +} + +// NewListEnterprisesParamsWithContext creates a new ListEnterprisesParams object +// with the ability to set a context for a request. +func NewListEnterprisesParamsWithContext(ctx context.Context) *ListEnterprisesParams { + return &ListEnterprisesParams{ + Context: ctx, + } +} + +// NewListEnterprisesParamsWithHTTPClient creates a new ListEnterprisesParams object +// with the ability to set a custom HTTPClient for a request. +func NewListEnterprisesParamsWithHTTPClient(client *http.Client) *ListEnterprisesParams { + return &ListEnterprisesParams{ + HTTPClient: client, + } +} + +/* +ListEnterprisesParams contains all the parameters to send to the API endpoint + + for the list enterprises operation. + + Typically these are written to a http.Request. +*/ +type ListEnterprisesParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the list enterprises params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListEnterprisesParams) WithDefaults() *ListEnterprisesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the list enterprises params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListEnterprisesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the list enterprises params +func (o *ListEnterprisesParams) WithTimeout(timeout time.Duration) *ListEnterprisesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list enterprises params +func (o *ListEnterprisesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list enterprises params +func (o *ListEnterprisesParams) WithContext(ctx context.Context) *ListEnterprisesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list enterprises params +func (o *ListEnterprisesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list enterprises params +func (o *ListEnterprisesParams) WithHTTPClient(client *http.Client) *ListEnterprisesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list enterprises params +func (o *ListEnterprisesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListEnterprisesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/enterprises/list_enterprises_responses.go b/client/enterprises/list_enterprises_responses.go new file mode 100644 index 00000000..1bb58307 --- /dev/null +++ b/client/enterprises/list_enterprises_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// ListEnterprisesReader is a Reader for the ListEnterprises structure. +type ListEnterprisesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListEnterprisesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListEnterprisesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewListEnterprisesDefault(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 + } +} + +// NewListEnterprisesOK creates a ListEnterprisesOK with default headers values +func NewListEnterprisesOK() *ListEnterprisesOK { + return &ListEnterprisesOK{} +} + +/* +ListEnterprisesOK describes a response with status code 200, with default header values. + +Enterprises +*/ +type ListEnterprisesOK struct { + Payload garm_params.Enterprises +} + +// IsSuccess returns true when this list enterprises o k response has a 2xx status code +func (o *ListEnterprisesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this list enterprises o k response has a 3xx status code +func (o *ListEnterprisesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list enterprises o k response has a 4xx status code +func (o *ListEnterprisesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this list enterprises o k response has a 5xx status code +func (o *ListEnterprisesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this list enterprises o k response a status code equal to that given +func (o *ListEnterprisesOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the list enterprises o k response +func (o *ListEnterprisesOK) Code() int { + return 200 +} + +func (o *ListEnterprisesOK) Error() string { + return fmt.Sprintf("[GET /enterprises][%d] listEnterprisesOK %+v", 200, o.Payload) +} + +func (o *ListEnterprisesOK) String() string { + return fmt.Sprintf("[GET /enterprises][%d] listEnterprisesOK %+v", 200, o.Payload) +} + +func (o *ListEnterprisesOK) GetPayload() garm_params.Enterprises { + return o.Payload +} + +func (o *ListEnterprisesOK) 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 +} + +// NewListEnterprisesDefault creates a ListEnterprisesDefault with default headers values +func NewListEnterprisesDefault(code int) *ListEnterprisesDefault { + return &ListEnterprisesDefault{ + _statusCode: code, + } +} + +/* +ListEnterprisesDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type ListEnterprisesDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this list enterprises default response has a 2xx status code +func (o *ListEnterprisesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this list enterprises default response has a 3xx status code +func (o *ListEnterprisesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this list enterprises default response has a 4xx status code +func (o *ListEnterprisesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this list enterprises default response has a 5xx status code +func (o *ListEnterprisesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this list enterprises default response a status code equal to that given +func (o *ListEnterprisesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the list enterprises default response +func (o *ListEnterprisesDefault) Code() int { + return o._statusCode +} + +func (o *ListEnterprisesDefault) Error() string { + return fmt.Sprintf("[GET /enterprises][%d] ListEnterprises default %+v", o._statusCode, o.Payload) +} + +func (o *ListEnterprisesDefault) String() string { + return fmt.Sprintf("[GET /enterprises][%d] ListEnterprises default %+v", o._statusCode, o.Payload) +} + +func (o *ListEnterprisesDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *ListEnterprisesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/enterprises/update_enterprise_parameters.go b/client/enterprises/update_enterprise_parameters.go new file mode 100644 index 00000000..2ad38eb6 --- /dev/null +++ b/client/enterprises/update_enterprise_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// NewUpdateEnterpriseParams creates a new UpdateEnterpriseParams 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 NewUpdateEnterpriseParams() *UpdateEnterpriseParams { + return &UpdateEnterpriseParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewUpdateEnterpriseParamsWithTimeout creates a new UpdateEnterpriseParams object +// with the ability to set a timeout on a request. +func NewUpdateEnterpriseParamsWithTimeout(timeout time.Duration) *UpdateEnterpriseParams { + return &UpdateEnterpriseParams{ + timeout: timeout, + } +} + +// NewUpdateEnterpriseParamsWithContext creates a new UpdateEnterpriseParams object +// with the ability to set a context for a request. +func NewUpdateEnterpriseParamsWithContext(ctx context.Context) *UpdateEnterpriseParams { + return &UpdateEnterpriseParams{ + Context: ctx, + } +} + +// NewUpdateEnterpriseParamsWithHTTPClient creates a new UpdateEnterpriseParams object +// with the ability to set a custom HTTPClient for a request. +func NewUpdateEnterpriseParamsWithHTTPClient(client *http.Client) *UpdateEnterpriseParams { + return &UpdateEnterpriseParams{ + HTTPClient: client, + } +} + +/* +UpdateEnterpriseParams contains all the parameters to send to the API endpoint + + for the update enterprise operation. + + Typically these are written to a http.Request. +*/ +type UpdateEnterpriseParams struct { + + /* Body. + + Parameters used when updating the enterprise. + */ + Body garm_params.UpdateEntityParams + + /* EnterpriseID. + + The ID of the enterprise to update. + */ + EnterpriseID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the update enterprise params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UpdateEnterpriseParams) WithDefaults() *UpdateEnterpriseParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the update enterprise params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UpdateEnterpriseParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the update enterprise params +func (o *UpdateEnterpriseParams) WithTimeout(timeout time.Duration) *UpdateEnterpriseParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the update enterprise params +func (o *UpdateEnterpriseParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the update enterprise params +func (o *UpdateEnterpriseParams) WithContext(ctx context.Context) *UpdateEnterpriseParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the update enterprise params +func (o *UpdateEnterpriseParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the update enterprise params +func (o *UpdateEnterpriseParams) WithHTTPClient(client *http.Client) *UpdateEnterpriseParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the update enterprise params +func (o *UpdateEnterpriseParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the update enterprise params +func (o *UpdateEnterpriseParams) WithBody(body garm_params.UpdateEntityParams) *UpdateEnterpriseParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the update enterprise params +func (o *UpdateEnterpriseParams) SetBody(body garm_params.UpdateEntityParams) { + o.Body = body +} + +// WithEnterpriseID adds the enterpriseID to the update enterprise params +func (o *UpdateEnterpriseParams) WithEnterpriseID(enterpriseID string) *UpdateEnterpriseParams { + o.SetEnterpriseID(enterpriseID) + return o +} + +// SetEnterpriseID adds the enterpriseId to the update enterprise params +func (o *UpdateEnterpriseParams) SetEnterpriseID(enterpriseID string) { + o.EnterpriseID = enterpriseID +} + +// WriteToRequest writes these params to a swagger request +func (o *UpdateEnterpriseParams) 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 enterpriseID + if err := r.SetPathParam("enterpriseID", o.EnterpriseID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/enterprises/update_enterprise_pool_parameters.go b/client/enterprises/update_enterprise_pool_parameters.go new file mode 100644 index 00000000..7940eb54 --- /dev/null +++ b/client/enterprises/update_enterprise_pool_parameters.go @@ -0,0 +1,195 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// NewUpdateEnterprisePoolParams creates a new UpdateEnterprisePoolParams 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 NewUpdateEnterprisePoolParams() *UpdateEnterprisePoolParams { + return &UpdateEnterprisePoolParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewUpdateEnterprisePoolParamsWithTimeout creates a new UpdateEnterprisePoolParams object +// with the ability to set a timeout on a request. +func NewUpdateEnterprisePoolParamsWithTimeout(timeout time.Duration) *UpdateEnterprisePoolParams { + return &UpdateEnterprisePoolParams{ + timeout: timeout, + } +} + +// NewUpdateEnterprisePoolParamsWithContext creates a new UpdateEnterprisePoolParams object +// with the ability to set a context for a request. +func NewUpdateEnterprisePoolParamsWithContext(ctx context.Context) *UpdateEnterprisePoolParams { + return &UpdateEnterprisePoolParams{ + Context: ctx, + } +} + +// NewUpdateEnterprisePoolParamsWithHTTPClient creates a new UpdateEnterprisePoolParams object +// with the ability to set a custom HTTPClient for a request. +func NewUpdateEnterprisePoolParamsWithHTTPClient(client *http.Client) *UpdateEnterprisePoolParams { + return &UpdateEnterprisePoolParams{ + HTTPClient: client, + } +} + +/* +UpdateEnterprisePoolParams contains all the parameters to send to the API endpoint + + for the update enterprise pool operation. + + Typically these are written to a http.Request. +*/ +type UpdateEnterprisePoolParams struct { + + /* Body. + + Parameters used when updating the enterprise pool. + */ + Body garm_params.UpdatePoolParams + + /* EnterpriseID. + + Enterprise ID. + */ + EnterpriseID string + + /* PoolID. + + ID of the enterprise pool to update. + */ + PoolID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the update enterprise pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UpdateEnterprisePoolParams) WithDefaults() *UpdateEnterprisePoolParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the update enterprise pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UpdateEnterprisePoolParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the update enterprise pool params +func (o *UpdateEnterprisePoolParams) WithTimeout(timeout time.Duration) *UpdateEnterprisePoolParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the update enterprise pool params +func (o *UpdateEnterprisePoolParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the update enterprise pool params +func (o *UpdateEnterprisePoolParams) WithContext(ctx context.Context) *UpdateEnterprisePoolParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the update enterprise pool params +func (o *UpdateEnterprisePoolParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the update enterprise pool params +func (o *UpdateEnterprisePoolParams) WithHTTPClient(client *http.Client) *UpdateEnterprisePoolParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the update enterprise pool params +func (o *UpdateEnterprisePoolParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the update enterprise pool params +func (o *UpdateEnterprisePoolParams) WithBody(body garm_params.UpdatePoolParams) *UpdateEnterprisePoolParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the update enterprise pool params +func (o *UpdateEnterprisePoolParams) SetBody(body garm_params.UpdatePoolParams) { + o.Body = body +} + +// WithEnterpriseID adds the enterpriseID to the update enterprise pool params +func (o *UpdateEnterprisePoolParams) WithEnterpriseID(enterpriseID string) *UpdateEnterprisePoolParams { + o.SetEnterpriseID(enterpriseID) + return o +} + +// SetEnterpriseID adds the enterpriseId to the update enterprise pool params +func (o *UpdateEnterprisePoolParams) SetEnterpriseID(enterpriseID string) { + o.EnterpriseID = enterpriseID +} + +// WithPoolID adds the poolID to the update enterprise pool params +func (o *UpdateEnterprisePoolParams) WithPoolID(poolID string) *UpdateEnterprisePoolParams { + o.SetPoolID(poolID) + return o +} + +// SetPoolID adds the poolId to the update enterprise pool params +func (o *UpdateEnterprisePoolParams) SetPoolID(poolID string) { + o.PoolID = poolID +} + +// WriteToRequest writes these params to a swagger request +func (o *UpdateEnterprisePoolParams) 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 enterpriseID + if err := r.SetPathParam("enterpriseID", o.EnterpriseID); err != nil { + return err + } + + // path param poolID + if err := r.SetPathParam("poolID", o.PoolID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/enterprises/update_enterprise_pool_responses.go b/client/enterprises/update_enterprise_pool_responses.go new file mode 100644 index 00000000..e20a51c8 --- /dev/null +++ b/client/enterprises/update_enterprise_pool_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// UpdateEnterprisePoolReader is a Reader for the UpdateEnterprisePool structure. +type UpdateEnterprisePoolReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UpdateEnterprisePoolReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUpdateEnterprisePoolOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewUpdateEnterprisePoolDefault(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 + } +} + +// NewUpdateEnterprisePoolOK creates a UpdateEnterprisePoolOK with default headers values +func NewUpdateEnterprisePoolOK() *UpdateEnterprisePoolOK { + return &UpdateEnterprisePoolOK{} +} + +/* +UpdateEnterprisePoolOK describes a response with status code 200, with default header values. + +Pool +*/ +type UpdateEnterprisePoolOK struct { + Payload garm_params.Pool +} + +// IsSuccess returns true when this update enterprise pool o k response has a 2xx status code +func (o *UpdateEnterprisePoolOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this update enterprise pool o k response has a 3xx status code +func (o *UpdateEnterprisePoolOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this update enterprise pool o k response has a 4xx status code +func (o *UpdateEnterprisePoolOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this update enterprise pool o k response has a 5xx status code +func (o *UpdateEnterprisePoolOK) IsServerError() bool { + return false +} + +// IsCode returns true when this update enterprise pool o k response a status code equal to that given +func (o *UpdateEnterprisePoolOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the update enterprise pool o k response +func (o *UpdateEnterprisePoolOK) Code() int { + return 200 +} + +func (o *UpdateEnterprisePoolOK) Error() string { + return fmt.Sprintf("[PUT /enterprises/{enterpriseID}/pools/{poolID}][%d] updateEnterprisePoolOK %+v", 200, o.Payload) +} + +func (o *UpdateEnterprisePoolOK) String() string { + return fmt.Sprintf("[PUT /enterprises/{enterpriseID}/pools/{poolID}][%d] updateEnterprisePoolOK %+v", 200, o.Payload) +} + +func (o *UpdateEnterprisePoolOK) GetPayload() garm_params.Pool { + return o.Payload +} + +func (o *UpdateEnterprisePoolOK) 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 +} + +// NewUpdateEnterprisePoolDefault creates a UpdateEnterprisePoolDefault with default headers values +func NewUpdateEnterprisePoolDefault(code int) *UpdateEnterprisePoolDefault { + return &UpdateEnterprisePoolDefault{ + _statusCode: code, + } +} + +/* +UpdateEnterprisePoolDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type UpdateEnterprisePoolDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this update enterprise pool default response has a 2xx status code +func (o *UpdateEnterprisePoolDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this update enterprise pool default response has a 3xx status code +func (o *UpdateEnterprisePoolDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this update enterprise pool default response has a 4xx status code +func (o *UpdateEnterprisePoolDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this update enterprise pool default response has a 5xx status code +func (o *UpdateEnterprisePoolDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this update enterprise pool default response a status code equal to that given +func (o *UpdateEnterprisePoolDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the update enterprise pool default response +func (o *UpdateEnterprisePoolDefault) Code() int { + return o._statusCode +} + +func (o *UpdateEnterprisePoolDefault) Error() string { + return fmt.Sprintf("[PUT /enterprises/{enterpriseID}/pools/{poolID}][%d] UpdateEnterprisePool default %+v", o._statusCode, o.Payload) +} + +func (o *UpdateEnterprisePoolDefault) String() string { + return fmt.Sprintf("[PUT /enterprises/{enterpriseID}/pools/{poolID}][%d] UpdateEnterprisePool default %+v", o._statusCode, o.Payload) +} + +func (o *UpdateEnterprisePoolDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *UpdateEnterprisePoolDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/enterprises/update_enterprise_responses.go b/client/enterprises/update_enterprise_responses.go new file mode 100644 index 00000000..3bea3347 --- /dev/null +++ b/client/enterprises/update_enterprise_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package enterprises + +// 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" +) + +// UpdateEnterpriseReader is a Reader for the UpdateEnterprise structure. +type UpdateEnterpriseReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UpdateEnterpriseReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUpdateEnterpriseOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewUpdateEnterpriseDefault(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 + } +} + +// NewUpdateEnterpriseOK creates a UpdateEnterpriseOK with default headers values +func NewUpdateEnterpriseOK() *UpdateEnterpriseOK { + return &UpdateEnterpriseOK{} +} + +/* +UpdateEnterpriseOK describes a response with status code 200, with default header values. + +Enterprise +*/ +type UpdateEnterpriseOK struct { + Payload garm_params.Enterprise +} + +// IsSuccess returns true when this update enterprise o k response has a 2xx status code +func (o *UpdateEnterpriseOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this update enterprise o k response has a 3xx status code +func (o *UpdateEnterpriseOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this update enterprise o k response has a 4xx status code +func (o *UpdateEnterpriseOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this update enterprise o k response has a 5xx status code +func (o *UpdateEnterpriseOK) IsServerError() bool { + return false +} + +// IsCode returns true when this update enterprise o k response a status code equal to that given +func (o *UpdateEnterpriseOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the update enterprise o k response +func (o *UpdateEnterpriseOK) Code() int { + return 200 +} + +func (o *UpdateEnterpriseOK) Error() string { + return fmt.Sprintf("[PUT /enterprises/{enterpriseID}][%d] updateEnterpriseOK %+v", 200, o.Payload) +} + +func (o *UpdateEnterpriseOK) String() string { + return fmt.Sprintf("[PUT /enterprises/{enterpriseID}][%d] updateEnterpriseOK %+v", 200, o.Payload) +} + +func (o *UpdateEnterpriseOK) GetPayload() garm_params.Enterprise { + return o.Payload +} + +func (o *UpdateEnterpriseOK) 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 +} + +// NewUpdateEnterpriseDefault creates a UpdateEnterpriseDefault with default headers values +func NewUpdateEnterpriseDefault(code int) *UpdateEnterpriseDefault { + return &UpdateEnterpriseDefault{ + _statusCode: code, + } +} + +/* +UpdateEnterpriseDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type UpdateEnterpriseDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this update enterprise default response has a 2xx status code +func (o *UpdateEnterpriseDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this update enterprise default response has a 3xx status code +func (o *UpdateEnterpriseDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this update enterprise default response has a 4xx status code +func (o *UpdateEnterpriseDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this update enterprise default response has a 5xx status code +func (o *UpdateEnterpriseDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this update enterprise default response a status code equal to that given +func (o *UpdateEnterpriseDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the update enterprise default response +func (o *UpdateEnterpriseDefault) Code() int { + return o._statusCode +} + +func (o *UpdateEnterpriseDefault) Error() string { + return fmt.Sprintf("[PUT /enterprises/{enterpriseID}][%d] UpdateEnterprise default %+v", o._statusCode, o.Payload) +} + +func (o *UpdateEnterpriseDefault) String() string { + return fmt.Sprintf("[PUT /enterprises/{enterpriseID}][%d] UpdateEnterprise default %+v", o._statusCode, o.Payload) +} + +func (o *UpdateEnterpriseDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *UpdateEnterpriseDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/first_run/first_run_client.go b/client/first_run/first_run_client.go new file mode 100644 index 00000000..9066a56e --- /dev/null +++ b/client/first_run/first_run_client.go @@ -0,0 +1,80 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package first_run + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new first run API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for first run 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 { + FirstRun(params *FirstRunParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*FirstRunOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +FirstRun initializes the first run of the controller +*/ +func (a *Client) FirstRun(params *FirstRunParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*FirstRunOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewFirstRunParams() + } + op := &runtime.ClientOperation{ + ID: "FirstRun", + Method: "POST", + PathPattern: "/first-run", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &FirstRunReader{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.(*FirstRunOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for FirstRun: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/client/first_run/first_run_parameters.go b/client/first_run/first_run_parameters.go new file mode 100644 index 00000000..5d3b91fd --- /dev/null +++ b/client/first_run/first_run_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package first_run + +// 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" +) + +// NewFirstRunParams creates a new FirstRunParams 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 NewFirstRunParams() *FirstRunParams { + return &FirstRunParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewFirstRunParamsWithTimeout creates a new FirstRunParams object +// with the ability to set a timeout on a request. +func NewFirstRunParamsWithTimeout(timeout time.Duration) *FirstRunParams { + return &FirstRunParams{ + timeout: timeout, + } +} + +// NewFirstRunParamsWithContext creates a new FirstRunParams object +// with the ability to set a context for a request. +func NewFirstRunParamsWithContext(ctx context.Context) *FirstRunParams { + return &FirstRunParams{ + Context: ctx, + } +} + +// NewFirstRunParamsWithHTTPClient creates a new FirstRunParams object +// with the ability to set a custom HTTPClient for a request. +func NewFirstRunParamsWithHTTPClient(client *http.Client) *FirstRunParams { + return &FirstRunParams{ + HTTPClient: client, + } +} + +/* +FirstRunParams contains all the parameters to send to the API endpoint + + for the first run operation. + + Typically these are written to a http.Request. +*/ +type FirstRunParams struct { + + /* Body. + + Create a new user. + */ + Body garm_params.NewUserParams + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the first run params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *FirstRunParams) WithDefaults() *FirstRunParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the first run params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *FirstRunParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the first run params +func (o *FirstRunParams) WithTimeout(timeout time.Duration) *FirstRunParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the first run params +func (o *FirstRunParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the first run params +func (o *FirstRunParams) WithContext(ctx context.Context) *FirstRunParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the first run params +func (o *FirstRunParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the first run params +func (o *FirstRunParams) WithHTTPClient(client *http.Client) *FirstRunParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the first run params +func (o *FirstRunParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the first run params +func (o *FirstRunParams) WithBody(body garm_params.NewUserParams) *FirstRunParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the first run params +func (o *FirstRunParams) SetBody(body garm_params.NewUserParams) { + o.Body = body +} + +// WriteToRequest writes these params to a swagger request +func (o *FirstRunParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/first_run/first_run_responses.go b/client/first_run/first_run_responses.go new file mode 100644 index 00000000..9057d7ee --- /dev/null +++ b/client/first_run/first_run_responses.go @@ -0,0 +1,174 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package first_run + +// 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" +) + +// FirstRunReader is a Reader for the FirstRun structure. +type FirstRunReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *FirstRunReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewFirstRunOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewFirstRunBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /first-run] FirstRun", response, response.Code()) + } +} + +// NewFirstRunOK creates a FirstRunOK with default headers values +func NewFirstRunOK() *FirstRunOK { + return &FirstRunOK{} +} + +/* +FirstRunOK describes a response with status code 200, with default header values. + +User +*/ +type FirstRunOK struct { + Payload garm_params.User +} + +// IsSuccess returns true when this first run o k response has a 2xx status code +func (o *FirstRunOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this first run o k response has a 3xx status code +func (o *FirstRunOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this first run o k response has a 4xx status code +func (o *FirstRunOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this first run o k response has a 5xx status code +func (o *FirstRunOK) IsServerError() bool { + return false +} + +// IsCode returns true when this first run o k response a status code equal to that given +func (o *FirstRunOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the first run o k response +func (o *FirstRunOK) Code() int { + return 200 +} + +func (o *FirstRunOK) Error() string { + return fmt.Sprintf("[POST /first-run][%d] firstRunOK %+v", 200, o.Payload) +} + +func (o *FirstRunOK) String() string { + return fmt.Sprintf("[POST /first-run][%d] firstRunOK %+v", 200, o.Payload) +} + +func (o *FirstRunOK) GetPayload() garm_params.User { + return o.Payload +} + +func (o *FirstRunOK) 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 +} + +// NewFirstRunBadRequest creates a FirstRunBadRequest with default headers values +func NewFirstRunBadRequest() *FirstRunBadRequest { + return &FirstRunBadRequest{} +} + +/* +FirstRunBadRequest describes a response with status code 400, with default header values. + +APIErrorResponse +*/ +type FirstRunBadRequest struct { + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this first run bad request response has a 2xx status code +func (o *FirstRunBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this first run bad request response has a 3xx status code +func (o *FirstRunBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this first run bad request response has a 4xx status code +func (o *FirstRunBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this first run bad request response has a 5xx status code +func (o *FirstRunBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this first run bad request response a status code equal to that given +func (o *FirstRunBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the first run bad request response +func (o *FirstRunBadRequest) Code() int { + return 400 +} + +func (o *FirstRunBadRequest) Error() string { + return fmt.Sprintf("[POST /first-run][%d] firstRunBadRequest %+v", 400, o.Payload) +} + +func (o *FirstRunBadRequest) String() string { + return fmt.Sprintf("[POST /first-run][%d] firstRunBadRequest %+v", 400, o.Payload) +} + +func (o *FirstRunBadRequest) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *FirstRunBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/garm_api_client.go b/client/garm_api_client.go index eec535d5..0f9a208a 100644 --- a/client/garm_api_client.go +++ b/client/garm_api_client.go @@ -10,7 +10,16 @@ import ( httptransport "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" + "github.com/cloudbase/garm/client/credentials" + "github.com/cloudbase/garm/client/enterprises" + "github.com/cloudbase/garm/client/first_run" "github.com/cloudbase/garm/client/instances" + "github.com/cloudbase/garm/client/jobs" + "github.com/cloudbase/garm/client/login" + "github.com/cloudbase/garm/client/metrics_token" + "github.com/cloudbase/garm/client/organizations" + "github.com/cloudbase/garm/client/pools" + "github.com/cloudbase/garm/client/providers" "github.com/cloudbase/garm/client/repositories" ) @@ -56,7 +65,16 @@ func New(transport runtime.ClientTransport, formats strfmt.Registry) *GarmAPI { cli := new(GarmAPI) cli.Transport = transport + cli.Credentials = credentials.New(transport, formats) + cli.Enterprises = enterprises.New(transport, formats) + cli.FirstRun = first_run.New(transport, formats) cli.Instances = instances.New(transport, formats) + cli.Jobs = jobs.New(transport, formats) + cli.Login = login.New(transport, formats) + cli.MetricsToken = metrics_token.New(transport, formats) + cli.Organizations = organizations.New(transport, formats) + cli.Pools = pools.New(transport, formats) + cli.Providers = providers.New(transport, formats) cli.Repositories = repositories.New(transport, formats) return cli } @@ -102,8 +120,26 @@ func (cfg *TransportConfig) WithSchemes(schemes []string) *TransportConfig { // GarmAPI is a client for garm API type GarmAPI struct { + Credentials credentials.ClientService + + Enterprises enterprises.ClientService + + FirstRun first_run.ClientService + Instances instances.ClientService + Jobs jobs.ClientService + + Login login.ClientService + + MetricsToken metrics_token.ClientService + + Organizations organizations.ClientService + + Pools pools.ClientService + + Providers providers.ClientService + Repositories repositories.ClientService Transport runtime.ClientTransport @@ -112,6 +148,15 @@ type GarmAPI struct { // SetTransport changes the transport on the client and all its subresources func (c *GarmAPI) SetTransport(transport runtime.ClientTransport) { c.Transport = transport + c.Credentials.SetTransport(transport) + c.Enterprises.SetTransport(transport) + c.FirstRun.SetTransport(transport) c.Instances.SetTransport(transport) + c.Jobs.SetTransport(transport) + c.Login.SetTransport(transport) + c.MetricsToken.SetTransport(transport) + c.Organizations.SetTransport(transport) + c.Pools.SetTransport(transport) + c.Providers.SetTransport(transport) c.Repositories.SetTransport(transport) } diff --git a/client/instances/instances_client.go b/client/instances/instances_client.go index 44fd4dd2..fae1d7da 100644 --- a/client/instances/instances_client.go +++ b/client/instances/instances_client.go @@ -34,6 +34,8 @@ type ClientService interface { ListInstances(params *ListInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListInstancesOK, error) + ListPoolInstances(params *ListPoolInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListPoolInstancesOK, error) + SetTransport(transport runtime.ClientTransport) } @@ -145,6 +147,44 @@ func (a *Client) ListInstances(params *ListInstancesParams, authInfo runtime.Cli return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) } +/* +ListPoolInstances lists runner instances in a pool +*/ +func (a *Client) ListPoolInstances(params *ListPoolInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListPoolInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewListPoolInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "ListPoolInstances", + Method: "GET", + PathPattern: "/pools/{poolID}/instances", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ListPoolInstancesReader{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.(*ListPoolInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ListPoolInstancesDefault) + 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 diff --git a/client/instances/list_pool_instances_parameters.go b/client/instances/list_pool_instances_parameters.go new file mode 100644 index 00000000..622010de --- /dev/null +++ b/client/instances/list_pool_instances_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instances + +// 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" +) + +// NewListPoolInstancesParams creates a new ListPoolInstancesParams 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 NewListPoolInstancesParams() *ListPoolInstancesParams { + return &ListPoolInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewListPoolInstancesParamsWithTimeout creates a new ListPoolInstancesParams object +// with the ability to set a timeout on a request. +func NewListPoolInstancesParamsWithTimeout(timeout time.Duration) *ListPoolInstancesParams { + return &ListPoolInstancesParams{ + timeout: timeout, + } +} + +// NewListPoolInstancesParamsWithContext creates a new ListPoolInstancesParams object +// with the ability to set a context for a request. +func NewListPoolInstancesParamsWithContext(ctx context.Context) *ListPoolInstancesParams { + return &ListPoolInstancesParams{ + Context: ctx, + } +} + +// NewListPoolInstancesParamsWithHTTPClient creates a new ListPoolInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewListPoolInstancesParamsWithHTTPClient(client *http.Client) *ListPoolInstancesParams { + return &ListPoolInstancesParams{ + HTTPClient: client, + } +} + +/* +ListPoolInstancesParams contains all the parameters to send to the API endpoint + + for the list pool instances operation. + + Typically these are written to a http.Request. +*/ +type ListPoolInstancesParams struct { + + /* PoolID. + + Runner pool ID. + */ + PoolID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the list pool instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListPoolInstancesParams) WithDefaults() *ListPoolInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the list pool instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListPoolInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the list pool instances params +func (o *ListPoolInstancesParams) WithTimeout(timeout time.Duration) *ListPoolInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list pool instances params +func (o *ListPoolInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list pool instances params +func (o *ListPoolInstancesParams) WithContext(ctx context.Context) *ListPoolInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list pool instances params +func (o *ListPoolInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list pool instances params +func (o *ListPoolInstancesParams) WithHTTPClient(client *http.Client) *ListPoolInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list pool instances params +func (o *ListPoolInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithPoolID adds the poolID to the list pool instances params +func (o *ListPoolInstancesParams) WithPoolID(poolID string) *ListPoolInstancesParams { + o.SetPoolID(poolID) + return o +} + +// SetPoolID adds the poolId to the list pool instances params +func (o *ListPoolInstancesParams) SetPoolID(poolID string) { + o.PoolID = poolID +} + +// WriteToRequest writes these params to a swagger request +func (o *ListPoolInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param poolID + if err := r.SetPathParam("poolID", o.PoolID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/instances/list_pool_instances_responses.go b/client/instances/list_pool_instances_responses.go new file mode 100644 index 00000000..2a61ca06 --- /dev/null +++ b/client/instances/list_pool_instances_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package instances + +// 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" +) + +// ListPoolInstancesReader is a Reader for the ListPoolInstances structure. +type ListPoolInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListPoolInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListPoolInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewListPoolInstancesDefault(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 + } +} + +// NewListPoolInstancesOK creates a ListPoolInstancesOK with default headers values +func NewListPoolInstancesOK() *ListPoolInstancesOK { + return &ListPoolInstancesOK{} +} + +/* +ListPoolInstancesOK describes a response with status code 200, with default header values. + +Instances +*/ +type ListPoolInstancesOK struct { + Payload garm_params.Instances +} + +// IsSuccess returns true when this list pool instances o k response has a 2xx status code +func (o *ListPoolInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this list pool instances o k response has a 3xx status code +func (o *ListPoolInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list pool instances o k response has a 4xx status code +func (o *ListPoolInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this list pool instances o k response has a 5xx status code +func (o *ListPoolInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this list pool instances o k response a status code equal to that given +func (o *ListPoolInstancesOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the list pool instances o k response +func (o *ListPoolInstancesOK) Code() int { + return 200 +} + +func (o *ListPoolInstancesOK) Error() string { + return fmt.Sprintf("[GET /pools/{poolID}/instances][%d] listPoolInstancesOK %+v", 200, o.Payload) +} + +func (o *ListPoolInstancesOK) String() string { + return fmt.Sprintf("[GET /pools/{poolID}/instances][%d] listPoolInstancesOK %+v", 200, o.Payload) +} + +func (o *ListPoolInstancesOK) GetPayload() garm_params.Instances { + return o.Payload +} + +func (o *ListPoolInstancesOK) 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 +} + +// NewListPoolInstancesDefault creates a ListPoolInstancesDefault with default headers values +func NewListPoolInstancesDefault(code int) *ListPoolInstancesDefault { + return &ListPoolInstancesDefault{ + _statusCode: code, + } +} + +/* +ListPoolInstancesDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type ListPoolInstancesDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this list pool instances default response has a 2xx status code +func (o *ListPoolInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this list pool instances default response has a 3xx status code +func (o *ListPoolInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this list pool instances default response has a 4xx status code +func (o *ListPoolInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this list pool instances default response has a 5xx status code +func (o *ListPoolInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this list pool instances default response a status code equal to that given +func (o *ListPoolInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the list pool instances default response +func (o *ListPoolInstancesDefault) Code() int { + return o._statusCode +} + +func (o *ListPoolInstancesDefault) Error() string { + return fmt.Sprintf("[GET /pools/{poolID}/instances][%d] ListPoolInstances default %+v", o._statusCode, o.Payload) +} + +func (o *ListPoolInstancesDefault) String() string { + return fmt.Sprintf("[GET /pools/{poolID}/instances][%d] ListPoolInstances default %+v", o._statusCode, o.Payload) +} + +func (o *ListPoolInstancesDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *ListPoolInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/jobs/jobs_client.go b/client/jobs/jobs_client.go new file mode 100644 index 00000000..1058c5c7 --- /dev/null +++ b/client/jobs/jobs_client.go @@ -0,0 +1,80 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package jobs + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new jobs API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for jobs 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 { + ListJobs(params *ListJobsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListJobsOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +ListJobs lists all jobs +*/ +func (a *Client) ListJobs(params *ListJobsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListJobsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewListJobsParams() + } + op := &runtime.ClientOperation{ + ID: "ListJobs", + Method: "GET", + PathPattern: "/jobs", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ListJobsReader{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.(*ListJobsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for ListJobs: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/client/jobs/list_jobs_parameters.go b/client/jobs/list_jobs_parameters.go new file mode 100644 index 00000000..9f605015 --- /dev/null +++ b/client/jobs/list_jobs_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package jobs + +// 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" +) + +// NewListJobsParams creates a new ListJobsParams 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 NewListJobsParams() *ListJobsParams { + return &ListJobsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewListJobsParamsWithTimeout creates a new ListJobsParams object +// with the ability to set a timeout on a request. +func NewListJobsParamsWithTimeout(timeout time.Duration) *ListJobsParams { + return &ListJobsParams{ + timeout: timeout, + } +} + +// NewListJobsParamsWithContext creates a new ListJobsParams object +// with the ability to set a context for a request. +func NewListJobsParamsWithContext(ctx context.Context) *ListJobsParams { + return &ListJobsParams{ + Context: ctx, + } +} + +// NewListJobsParamsWithHTTPClient creates a new ListJobsParams object +// with the ability to set a custom HTTPClient for a request. +func NewListJobsParamsWithHTTPClient(client *http.Client) *ListJobsParams { + return &ListJobsParams{ + HTTPClient: client, + } +} + +/* +ListJobsParams contains all the parameters to send to the API endpoint + + for the list jobs operation. + + Typically these are written to a http.Request. +*/ +type ListJobsParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the list jobs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListJobsParams) WithDefaults() *ListJobsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the list jobs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListJobsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the list jobs params +func (o *ListJobsParams) WithTimeout(timeout time.Duration) *ListJobsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list jobs params +func (o *ListJobsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list jobs params +func (o *ListJobsParams) WithContext(ctx context.Context) *ListJobsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list jobs params +func (o *ListJobsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list jobs params +func (o *ListJobsParams) WithHTTPClient(client *http.Client) *ListJobsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list jobs params +func (o *ListJobsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListJobsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/jobs/list_jobs_responses.go b/client/jobs/list_jobs_responses.go new file mode 100644 index 00000000..63282dd4 --- /dev/null +++ b/client/jobs/list_jobs_responses.go @@ -0,0 +1,174 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package jobs + +// 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" +) + +// ListJobsReader is a Reader for the ListJobs structure. +type ListJobsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListJobsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListJobsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewListJobsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /jobs] ListJobs", response, response.Code()) + } +} + +// NewListJobsOK creates a ListJobsOK with default headers values +func NewListJobsOK() *ListJobsOK { + return &ListJobsOK{} +} + +/* +ListJobsOK describes a response with status code 200, with default header values. + +Jobs +*/ +type ListJobsOK struct { + Payload garm_params.Jobs +} + +// IsSuccess returns true when this list jobs o k response has a 2xx status code +func (o *ListJobsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this list jobs o k response has a 3xx status code +func (o *ListJobsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list jobs o k response has a 4xx status code +func (o *ListJobsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this list jobs o k response has a 5xx status code +func (o *ListJobsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this list jobs o k response a status code equal to that given +func (o *ListJobsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the list jobs o k response +func (o *ListJobsOK) Code() int { + return 200 +} + +func (o *ListJobsOK) Error() string { + return fmt.Sprintf("[GET /jobs][%d] listJobsOK %+v", 200, o.Payload) +} + +func (o *ListJobsOK) String() string { + return fmt.Sprintf("[GET /jobs][%d] listJobsOK %+v", 200, o.Payload) +} + +func (o *ListJobsOK) GetPayload() garm_params.Jobs { + return o.Payload +} + +func (o *ListJobsOK) 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 +} + +// NewListJobsBadRequest creates a ListJobsBadRequest with default headers values +func NewListJobsBadRequest() *ListJobsBadRequest { + return &ListJobsBadRequest{} +} + +/* +ListJobsBadRequest describes a response with status code 400, with default header values. + +APIErrorResponse +*/ +type ListJobsBadRequest struct { + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this list jobs bad request response has a 2xx status code +func (o *ListJobsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this list jobs bad request response has a 3xx status code +func (o *ListJobsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list jobs bad request response has a 4xx status code +func (o *ListJobsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this list jobs bad request response has a 5xx status code +func (o *ListJobsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this list jobs bad request response a status code equal to that given +func (o *ListJobsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the list jobs bad request response +func (o *ListJobsBadRequest) Code() int { + return 400 +} + +func (o *ListJobsBadRequest) Error() string { + return fmt.Sprintf("[GET /jobs][%d] listJobsBadRequest %+v", 400, o.Payload) +} + +func (o *ListJobsBadRequest) String() string { + return fmt.Sprintf("[GET /jobs][%d] listJobsBadRequest %+v", 400, o.Payload) +} + +func (o *ListJobsBadRequest) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *ListJobsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/login/login_client.go b/client/login/login_client.go new file mode 100644 index 00000000..d976042d --- /dev/null +++ b/client/login/login_client.go @@ -0,0 +1,80 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package login + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new login API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for login 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 { + Login(params *LoginParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*LoginOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +Login logs in a user and returns a j w t token +*/ +func (a *Client) Login(params *LoginParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*LoginOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewLoginParams() + } + op := &runtime.ClientOperation{ + ID: "Login", + Method: "POST", + PathPattern: "/auth/login", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &LoginReader{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.(*LoginOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for Login: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/client/login/login_parameters.go b/client/login/login_parameters.go new file mode 100644 index 00000000..02ea77bc --- /dev/null +++ b/client/login/login_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package login + +// 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" +) + +// NewLoginParams creates a new LoginParams 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 NewLoginParams() *LoginParams { + return &LoginParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewLoginParamsWithTimeout creates a new LoginParams object +// with the ability to set a timeout on a request. +func NewLoginParamsWithTimeout(timeout time.Duration) *LoginParams { + return &LoginParams{ + timeout: timeout, + } +} + +// NewLoginParamsWithContext creates a new LoginParams object +// with the ability to set a context for a request. +func NewLoginParamsWithContext(ctx context.Context) *LoginParams { + return &LoginParams{ + Context: ctx, + } +} + +// NewLoginParamsWithHTTPClient creates a new LoginParams object +// with the ability to set a custom HTTPClient for a request. +func NewLoginParamsWithHTTPClient(client *http.Client) *LoginParams { + return &LoginParams{ + HTTPClient: client, + } +} + +/* +LoginParams contains all the parameters to send to the API endpoint + + for the login operation. + + Typically these are written to a http.Request. +*/ +type LoginParams struct { + + /* Body. + + Login information. + */ + Body garm_params.PasswordLoginParams + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the login params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *LoginParams) WithDefaults() *LoginParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the login params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *LoginParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the login params +func (o *LoginParams) WithTimeout(timeout time.Duration) *LoginParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the login params +func (o *LoginParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the login params +func (o *LoginParams) WithContext(ctx context.Context) *LoginParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the login params +func (o *LoginParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the login params +func (o *LoginParams) WithHTTPClient(client *http.Client) *LoginParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the login params +func (o *LoginParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the login params +func (o *LoginParams) WithBody(body garm_params.PasswordLoginParams) *LoginParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the login params +func (o *LoginParams) SetBody(body garm_params.PasswordLoginParams) { + o.Body = body +} + +// WriteToRequest writes these params to a swagger request +func (o *LoginParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/login/login_responses.go b/client/login/login_responses.go new file mode 100644 index 00000000..7506e909 --- /dev/null +++ b/client/login/login_responses.go @@ -0,0 +1,174 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package login + +// 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" +) + +// LoginReader is a Reader for the Login structure. +type LoginReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *LoginReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewLoginOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewLoginBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /auth/login] Login", response, response.Code()) + } +} + +// NewLoginOK creates a LoginOK with default headers values +func NewLoginOK() *LoginOK { + return &LoginOK{} +} + +/* +LoginOK describes a response with status code 200, with default header values. + +JWTResponse +*/ +type LoginOK struct { + Payload garm_params.JWTResponse +} + +// IsSuccess returns true when this login o k response has a 2xx status code +func (o *LoginOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this login o k response has a 3xx status code +func (o *LoginOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this login o k response has a 4xx status code +func (o *LoginOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this login o k response has a 5xx status code +func (o *LoginOK) IsServerError() bool { + return false +} + +// IsCode returns true when this login o k response a status code equal to that given +func (o *LoginOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the login o k response +func (o *LoginOK) Code() int { + return 200 +} + +func (o *LoginOK) Error() string { + return fmt.Sprintf("[POST /auth/login][%d] loginOK %+v", 200, o.Payload) +} + +func (o *LoginOK) String() string { + return fmt.Sprintf("[POST /auth/login][%d] loginOK %+v", 200, o.Payload) +} + +func (o *LoginOK) GetPayload() garm_params.JWTResponse { + return o.Payload +} + +func (o *LoginOK) 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 +} + +// NewLoginBadRequest creates a LoginBadRequest with default headers values +func NewLoginBadRequest() *LoginBadRequest { + return &LoginBadRequest{} +} + +/* +LoginBadRequest describes a response with status code 400, with default header values. + +APIErrorResponse +*/ +type LoginBadRequest struct { + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this login bad request response has a 2xx status code +func (o *LoginBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this login bad request response has a 3xx status code +func (o *LoginBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this login bad request response has a 4xx status code +func (o *LoginBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this login bad request response has a 5xx status code +func (o *LoginBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this login bad request response a status code equal to that given +func (o *LoginBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the login bad request response +func (o *LoginBadRequest) Code() int { + return 400 +} + +func (o *LoginBadRequest) Error() string { + return fmt.Sprintf("[POST /auth/login][%d] loginBadRequest %+v", 400, o.Payload) +} + +func (o *LoginBadRequest) String() string { + return fmt.Sprintf("[POST /auth/login][%d] loginBadRequest %+v", 400, o.Payload) +} + +func (o *LoginBadRequest) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *LoginBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/metrics_token/get_metrics_token_parameters.go b/client/metrics_token/get_metrics_token_parameters.go new file mode 100644 index 00000000..5099e113 --- /dev/null +++ b/client/metrics_token/get_metrics_token_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package metrics_token + +// 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" +) + +// NewGetMetricsTokenParams creates a new GetMetricsTokenParams 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 NewGetMetricsTokenParams() *GetMetricsTokenParams { + return &GetMetricsTokenParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetMetricsTokenParamsWithTimeout creates a new GetMetricsTokenParams object +// with the ability to set a timeout on a request. +func NewGetMetricsTokenParamsWithTimeout(timeout time.Duration) *GetMetricsTokenParams { + return &GetMetricsTokenParams{ + timeout: timeout, + } +} + +// NewGetMetricsTokenParamsWithContext creates a new GetMetricsTokenParams object +// with the ability to set a context for a request. +func NewGetMetricsTokenParamsWithContext(ctx context.Context) *GetMetricsTokenParams { + return &GetMetricsTokenParams{ + Context: ctx, + } +} + +// NewGetMetricsTokenParamsWithHTTPClient creates a new GetMetricsTokenParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetMetricsTokenParamsWithHTTPClient(client *http.Client) *GetMetricsTokenParams { + return &GetMetricsTokenParams{ + HTTPClient: client, + } +} + +/* +GetMetricsTokenParams contains all the parameters to send to the API endpoint + + for the get metrics token operation. + + Typically these are written to a http.Request. +*/ +type GetMetricsTokenParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get metrics token params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMetricsTokenParams) WithDefaults() *GetMetricsTokenParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get metrics token params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetMetricsTokenParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get metrics token params +func (o *GetMetricsTokenParams) WithTimeout(timeout time.Duration) *GetMetricsTokenParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get metrics token params +func (o *GetMetricsTokenParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get metrics token params +func (o *GetMetricsTokenParams) WithContext(ctx context.Context) *GetMetricsTokenParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get metrics token params +func (o *GetMetricsTokenParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get metrics token params +func (o *GetMetricsTokenParams) WithHTTPClient(client *http.Client) *GetMetricsTokenParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get metrics token params +func (o *GetMetricsTokenParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *GetMetricsTokenParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/metrics_token/get_metrics_token_responses.go b/client/metrics_token/get_metrics_token_responses.go new file mode 100644 index 00000000..0625afb0 --- /dev/null +++ b/client/metrics_token/get_metrics_token_responses.go @@ -0,0 +1,174 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package metrics_token + +// 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" +) + +// GetMetricsTokenReader is a Reader for the GetMetricsToken structure. +type GetMetricsTokenReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetMetricsTokenReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetMetricsTokenOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 401: + result := NewGetMetricsTokenUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /metrics-token] GetMetricsToken", response, response.Code()) + } +} + +// NewGetMetricsTokenOK creates a GetMetricsTokenOK with default headers values +func NewGetMetricsTokenOK() *GetMetricsTokenOK { + return &GetMetricsTokenOK{} +} + +/* +GetMetricsTokenOK describes a response with status code 200, with default header values. + +JWTResponse +*/ +type GetMetricsTokenOK struct { + Payload garm_params.JWTResponse +} + +// IsSuccess returns true when this get metrics token o k response has a 2xx status code +func (o *GetMetricsTokenOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get metrics token o k response has a 3xx status code +func (o *GetMetricsTokenOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get metrics token o k response has a 4xx status code +func (o *GetMetricsTokenOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get metrics token o k response has a 5xx status code +func (o *GetMetricsTokenOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get metrics token o k response a status code equal to that given +func (o *GetMetricsTokenOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get metrics token o k response +func (o *GetMetricsTokenOK) Code() int { + return 200 +} + +func (o *GetMetricsTokenOK) Error() string { + return fmt.Sprintf("[GET /metrics-token][%d] getMetricsTokenOK %+v", 200, o.Payload) +} + +func (o *GetMetricsTokenOK) String() string { + return fmt.Sprintf("[GET /metrics-token][%d] getMetricsTokenOK %+v", 200, o.Payload) +} + +func (o *GetMetricsTokenOK) GetPayload() garm_params.JWTResponse { + return o.Payload +} + +func (o *GetMetricsTokenOK) 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 +} + +// NewGetMetricsTokenUnauthorized creates a GetMetricsTokenUnauthorized with default headers values +func NewGetMetricsTokenUnauthorized() *GetMetricsTokenUnauthorized { + return &GetMetricsTokenUnauthorized{} +} + +/* +GetMetricsTokenUnauthorized describes a response with status code 401, with default header values. + +APIErrorResponse +*/ +type GetMetricsTokenUnauthorized struct { + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this get metrics token unauthorized response has a 2xx status code +func (o *GetMetricsTokenUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get metrics token unauthorized response has a 3xx status code +func (o *GetMetricsTokenUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get metrics token unauthorized response has a 4xx status code +func (o *GetMetricsTokenUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get metrics token unauthorized response has a 5xx status code +func (o *GetMetricsTokenUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get metrics token unauthorized response a status code equal to that given +func (o *GetMetricsTokenUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get metrics token unauthorized response +func (o *GetMetricsTokenUnauthorized) Code() int { + return 401 +} + +func (o *GetMetricsTokenUnauthorized) Error() string { + return fmt.Sprintf("[GET /metrics-token][%d] getMetricsTokenUnauthorized %+v", 401, o.Payload) +} + +func (o *GetMetricsTokenUnauthorized) String() string { + return fmt.Sprintf("[GET /metrics-token][%d] getMetricsTokenUnauthorized %+v", 401, o.Payload) +} + +func (o *GetMetricsTokenUnauthorized) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *GetMetricsTokenUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/metrics_token/metrics_token_client.go b/client/metrics_token/metrics_token_client.go new file mode 100644 index 00000000..60baae75 --- /dev/null +++ b/client/metrics_token/metrics_token_client.go @@ -0,0 +1,80 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package metrics_token + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new metrics token API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for metrics token 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 { + GetMetricsToken(params *GetMetricsTokenParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMetricsTokenOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +GetMetricsToken returns a j w t token that can be used to access the metrics endpoint +*/ +func (a *Client) GetMetricsToken(params *GetMetricsTokenParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetMetricsTokenOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetMetricsTokenParams() + } + op := &runtime.ClientOperation{ + ID: "GetMetricsToken", + Method: "GET", + PathPattern: "/metrics-token", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetMetricsTokenReader{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.(*GetMetricsTokenOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetMetricsToken: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/client/organizations/create_org_parameters.go b/client/organizations/create_org_parameters.go new file mode 100644 index 00000000..bf183834 --- /dev/null +++ b/client/organizations/create_org_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// NewCreateOrgParams creates a new CreateOrgParams 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 NewCreateOrgParams() *CreateOrgParams { + return &CreateOrgParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateOrgParamsWithTimeout creates a new CreateOrgParams object +// with the ability to set a timeout on a request. +func NewCreateOrgParamsWithTimeout(timeout time.Duration) *CreateOrgParams { + return &CreateOrgParams{ + timeout: timeout, + } +} + +// NewCreateOrgParamsWithContext creates a new CreateOrgParams object +// with the ability to set a context for a request. +func NewCreateOrgParamsWithContext(ctx context.Context) *CreateOrgParams { + return &CreateOrgParams{ + Context: ctx, + } +} + +// NewCreateOrgParamsWithHTTPClient creates a new CreateOrgParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateOrgParamsWithHTTPClient(client *http.Client) *CreateOrgParams { + return &CreateOrgParams{ + HTTPClient: client, + } +} + +/* +CreateOrgParams contains all the parameters to send to the API endpoint + + for the create org operation. + + Typically these are written to a http.Request. +*/ +type CreateOrgParams struct { + + /* Body. + + Parameters used when creating the organization. + */ + Body garm_params.CreateOrgParams + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create org params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateOrgParams) WithDefaults() *CreateOrgParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create org params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateOrgParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create org params +func (o *CreateOrgParams) WithTimeout(timeout time.Duration) *CreateOrgParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create org params +func (o *CreateOrgParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create org params +func (o *CreateOrgParams) WithContext(ctx context.Context) *CreateOrgParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create org params +func (o *CreateOrgParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create org params +func (o *CreateOrgParams) WithHTTPClient(client *http.Client) *CreateOrgParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create org params +func (o *CreateOrgParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create org params +func (o *CreateOrgParams) WithBody(body garm_params.CreateOrgParams) *CreateOrgParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create org params +func (o *CreateOrgParams) SetBody(body garm_params.CreateOrgParams) { + o.Body = body +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateOrgParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if err := r.SetBodyParam(o.Body); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/organizations/create_org_pool_parameters.go b/client/organizations/create_org_pool_parameters.go new file mode 100644 index 00000000..1fc46998 --- /dev/null +++ b/client/organizations/create_org_pool_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// NewCreateOrgPoolParams creates a new CreateOrgPoolParams 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 NewCreateOrgPoolParams() *CreateOrgPoolParams { + return &CreateOrgPoolParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewCreateOrgPoolParamsWithTimeout creates a new CreateOrgPoolParams object +// with the ability to set a timeout on a request. +func NewCreateOrgPoolParamsWithTimeout(timeout time.Duration) *CreateOrgPoolParams { + return &CreateOrgPoolParams{ + timeout: timeout, + } +} + +// NewCreateOrgPoolParamsWithContext creates a new CreateOrgPoolParams object +// with the ability to set a context for a request. +func NewCreateOrgPoolParamsWithContext(ctx context.Context) *CreateOrgPoolParams { + return &CreateOrgPoolParams{ + Context: ctx, + } +} + +// NewCreateOrgPoolParamsWithHTTPClient creates a new CreateOrgPoolParams object +// with the ability to set a custom HTTPClient for a request. +func NewCreateOrgPoolParamsWithHTTPClient(client *http.Client) *CreateOrgPoolParams { + return &CreateOrgPoolParams{ + HTTPClient: client, + } +} + +/* +CreateOrgPoolParams contains all the parameters to send to the API endpoint + + for the create org pool operation. + + Typically these are written to a http.Request. +*/ +type CreateOrgPoolParams struct { + + /* Body. + + Parameters used when creating the organization pool. + */ + Body garm_params.CreatePoolParams + + /* OrgID. + + Organization ID. + */ + OrgID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the create org pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateOrgPoolParams) WithDefaults() *CreateOrgPoolParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the create org pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *CreateOrgPoolParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the create org pool params +func (o *CreateOrgPoolParams) WithTimeout(timeout time.Duration) *CreateOrgPoolParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create org pool params +func (o *CreateOrgPoolParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create org pool params +func (o *CreateOrgPoolParams) WithContext(ctx context.Context) *CreateOrgPoolParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create org pool params +func (o *CreateOrgPoolParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create org pool params +func (o *CreateOrgPoolParams) WithHTTPClient(client *http.Client) *CreateOrgPoolParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create org pool params +func (o *CreateOrgPoolParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the create org pool params +func (o *CreateOrgPoolParams) WithBody(body garm_params.CreatePoolParams) *CreateOrgPoolParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the create org pool params +func (o *CreateOrgPoolParams) SetBody(body garm_params.CreatePoolParams) { + o.Body = body +} + +// WithOrgID adds the orgID to the create org pool params +func (o *CreateOrgPoolParams) WithOrgID(orgID string) *CreateOrgPoolParams { + o.SetOrgID(orgID) + return o +} + +// SetOrgID adds the orgId to the create org pool params +func (o *CreateOrgPoolParams) SetOrgID(orgID string) { + o.OrgID = orgID +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateOrgPoolParams) 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 orgID + if err := r.SetPathParam("orgID", o.OrgID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/organizations/create_org_pool_responses.go b/client/organizations/create_org_pool_responses.go new file mode 100644 index 00000000..d9d77022 --- /dev/null +++ b/client/organizations/create_org_pool_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// CreateOrgPoolReader is a Reader for the CreateOrgPool structure. +type CreateOrgPoolReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateOrgPoolReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateOrgPoolOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateOrgPoolDefault(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 + } +} + +// NewCreateOrgPoolOK creates a CreateOrgPoolOK with default headers values +func NewCreateOrgPoolOK() *CreateOrgPoolOK { + return &CreateOrgPoolOK{} +} + +/* +CreateOrgPoolOK describes a response with status code 200, with default header values. + +Pool +*/ +type CreateOrgPoolOK struct { + Payload garm_params.Pool +} + +// IsSuccess returns true when this create org pool o k response has a 2xx status code +func (o *CreateOrgPoolOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create org pool o k response has a 3xx status code +func (o *CreateOrgPoolOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create org pool o k response has a 4xx status code +func (o *CreateOrgPoolOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create org pool o k response has a 5xx status code +func (o *CreateOrgPoolOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create org pool o k response a status code equal to that given +func (o *CreateOrgPoolOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the create org pool o k response +func (o *CreateOrgPoolOK) Code() int { + return 200 +} + +func (o *CreateOrgPoolOK) Error() string { + return fmt.Sprintf("[POST /organizations/{orgID}/pools][%d] createOrgPoolOK %+v", 200, o.Payload) +} + +func (o *CreateOrgPoolOK) String() string { + return fmt.Sprintf("[POST /organizations/{orgID}/pools][%d] createOrgPoolOK %+v", 200, o.Payload) +} + +func (o *CreateOrgPoolOK) GetPayload() garm_params.Pool { + return o.Payload +} + +func (o *CreateOrgPoolOK) 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 +} + +// NewCreateOrgPoolDefault creates a CreateOrgPoolDefault with default headers values +func NewCreateOrgPoolDefault(code int) *CreateOrgPoolDefault { + return &CreateOrgPoolDefault{ + _statusCode: code, + } +} + +/* +CreateOrgPoolDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type CreateOrgPoolDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this create org pool default response has a 2xx status code +func (o *CreateOrgPoolDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create org pool default response has a 3xx status code +func (o *CreateOrgPoolDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create org pool default response has a 4xx status code +func (o *CreateOrgPoolDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create org pool default response has a 5xx status code +func (o *CreateOrgPoolDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create org pool default response a status code equal to that given +func (o *CreateOrgPoolDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the create org pool default response +func (o *CreateOrgPoolDefault) Code() int { + return o._statusCode +} + +func (o *CreateOrgPoolDefault) Error() string { + return fmt.Sprintf("[POST /organizations/{orgID}/pools][%d] CreateOrgPool default %+v", o._statusCode, o.Payload) +} + +func (o *CreateOrgPoolDefault) String() string { + return fmt.Sprintf("[POST /organizations/{orgID}/pools][%d] CreateOrgPool default %+v", o._statusCode, o.Payload) +} + +func (o *CreateOrgPoolDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *CreateOrgPoolDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/organizations/create_org_responses.go b/client/organizations/create_org_responses.go new file mode 100644 index 00000000..f8858716 --- /dev/null +++ b/client/organizations/create_org_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// CreateOrgReader is a Reader for the CreateOrg structure. +type CreateOrgReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateOrgReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewCreateOrgOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewCreateOrgDefault(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 + } +} + +// NewCreateOrgOK creates a CreateOrgOK with default headers values +func NewCreateOrgOK() *CreateOrgOK { + return &CreateOrgOK{} +} + +/* +CreateOrgOK describes a response with status code 200, with default header values. + +Organization +*/ +type CreateOrgOK struct { + Payload garm_params.Organization +} + +// IsSuccess returns true when this create org o k response has a 2xx status code +func (o *CreateOrgOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this create org o k response has a 3xx status code +func (o *CreateOrgOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this create org o k response has a 4xx status code +func (o *CreateOrgOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this create org o k response has a 5xx status code +func (o *CreateOrgOK) IsServerError() bool { + return false +} + +// IsCode returns true when this create org o k response a status code equal to that given +func (o *CreateOrgOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the create org o k response +func (o *CreateOrgOK) Code() int { + return 200 +} + +func (o *CreateOrgOK) Error() string { + return fmt.Sprintf("[POST /organizations][%d] createOrgOK %+v", 200, o.Payload) +} + +func (o *CreateOrgOK) String() string { + return fmt.Sprintf("[POST /organizations][%d] createOrgOK %+v", 200, o.Payload) +} + +func (o *CreateOrgOK) GetPayload() garm_params.Organization { + return o.Payload +} + +func (o *CreateOrgOK) 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 +} + +// NewCreateOrgDefault creates a CreateOrgDefault with default headers values +func NewCreateOrgDefault(code int) *CreateOrgDefault { + return &CreateOrgDefault{ + _statusCode: code, + } +} + +/* +CreateOrgDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type CreateOrgDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this create org default response has a 2xx status code +func (o *CreateOrgDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this create org default response has a 3xx status code +func (o *CreateOrgDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this create org default response has a 4xx status code +func (o *CreateOrgDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this create org default response has a 5xx status code +func (o *CreateOrgDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this create org default response a status code equal to that given +func (o *CreateOrgDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the create org default response +func (o *CreateOrgDefault) Code() int { + return o._statusCode +} + +func (o *CreateOrgDefault) Error() string { + return fmt.Sprintf("[POST /organizations][%d] CreateOrg default %+v", o._statusCode, o.Payload) +} + +func (o *CreateOrgDefault) String() string { + return fmt.Sprintf("[POST /organizations][%d] CreateOrg default %+v", o._statusCode, o.Payload) +} + +func (o *CreateOrgDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *CreateOrgDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/organizations/delete_org_parameters.go b/client/organizations/delete_org_parameters.go new file mode 100644 index 00000000..92e27495 --- /dev/null +++ b/client/organizations/delete_org_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// NewDeleteOrgParams creates a new DeleteOrgParams 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 NewDeleteOrgParams() *DeleteOrgParams { + return &DeleteOrgParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteOrgParamsWithTimeout creates a new DeleteOrgParams object +// with the ability to set a timeout on a request. +func NewDeleteOrgParamsWithTimeout(timeout time.Duration) *DeleteOrgParams { + return &DeleteOrgParams{ + timeout: timeout, + } +} + +// NewDeleteOrgParamsWithContext creates a new DeleteOrgParams object +// with the ability to set a context for a request. +func NewDeleteOrgParamsWithContext(ctx context.Context) *DeleteOrgParams { + return &DeleteOrgParams{ + Context: ctx, + } +} + +// NewDeleteOrgParamsWithHTTPClient creates a new DeleteOrgParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteOrgParamsWithHTTPClient(client *http.Client) *DeleteOrgParams { + return &DeleteOrgParams{ + HTTPClient: client, + } +} + +/* +DeleteOrgParams contains all the parameters to send to the API endpoint + + for the delete org operation. + + Typically these are written to a http.Request. +*/ +type DeleteOrgParams struct { + + /* OrgID. + + ID of the organization to delete. + */ + OrgID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete org params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteOrgParams) WithDefaults() *DeleteOrgParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete org params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteOrgParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete org params +func (o *DeleteOrgParams) WithTimeout(timeout time.Duration) *DeleteOrgParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete org params +func (o *DeleteOrgParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete org params +func (o *DeleteOrgParams) WithContext(ctx context.Context) *DeleteOrgParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete org params +func (o *DeleteOrgParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete org params +func (o *DeleteOrgParams) WithHTTPClient(client *http.Client) *DeleteOrgParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete org params +func (o *DeleteOrgParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithOrgID adds the orgID to the delete org params +func (o *DeleteOrgParams) WithOrgID(orgID string) *DeleteOrgParams { + o.SetOrgID(orgID) + return o +} + +// SetOrgID adds the orgId to the delete org params +func (o *DeleteOrgParams) SetOrgID(orgID string) { + o.OrgID = orgID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteOrgParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param orgID + if err := r.SetPathParam("orgID", o.OrgID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/organizations/delete_org_pool_parameters.go b/client/organizations/delete_org_pool_parameters.go new file mode 100644 index 00000000..89500172 --- /dev/null +++ b/client/organizations/delete_org_pool_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// NewDeleteOrgPoolParams creates a new DeleteOrgPoolParams 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 NewDeleteOrgPoolParams() *DeleteOrgPoolParams { + return &DeleteOrgPoolParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteOrgPoolParamsWithTimeout creates a new DeleteOrgPoolParams object +// with the ability to set a timeout on a request. +func NewDeleteOrgPoolParamsWithTimeout(timeout time.Duration) *DeleteOrgPoolParams { + return &DeleteOrgPoolParams{ + timeout: timeout, + } +} + +// NewDeleteOrgPoolParamsWithContext creates a new DeleteOrgPoolParams object +// with the ability to set a context for a request. +func NewDeleteOrgPoolParamsWithContext(ctx context.Context) *DeleteOrgPoolParams { + return &DeleteOrgPoolParams{ + Context: ctx, + } +} + +// NewDeleteOrgPoolParamsWithHTTPClient creates a new DeleteOrgPoolParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteOrgPoolParamsWithHTTPClient(client *http.Client) *DeleteOrgPoolParams { + return &DeleteOrgPoolParams{ + HTTPClient: client, + } +} + +/* +DeleteOrgPoolParams contains all the parameters to send to the API endpoint + + for the delete org pool operation. + + Typically these are written to a http.Request. +*/ +type DeleteOrgPoolParams struct { + + /* OrgID. + + Organization ID. + */ + OrgID string + + /* PoolID. + + ID of the organization pool to delete. + */ + PoolID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete org pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteOrgPoolParams) WithDefaults() *DeleteOrgPoolParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete org pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteOrgPoolParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete org pool params +func (o *DeleteOrgPoolParams) WithTimeout(timeout time.Duration) *DeleteOrgPoolParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete org pool params +func (o *DeleteOrgPoolParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete org pool params +func (o *DeleteOrgPoolParams) WithContext(ctx context.Context) *DeleteOrgPoolParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete org pool params +func (o *DeleteOrgPoolParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete org pool params +func (o *DeleteOrgPoolParams) WithHTTPClient(client *http.Client) *DeleteOrgPoolParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete org pool params +func (o *DeleteOrgPoolParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithOrgID adds the orgID to the delete org pool params +func (o *DeleteOrgPoolParams) WithOrgID(orgID string) *DeleteOrgPoolParams { + o.SetOrgID(orgID) + return o +} + +// SetOrgID adds the orgId to the delete org pool params +func (o *DeleteOrgPoolParams) SetOrgID(orgID string) { + o.OrgID = orgID +} + +// WithPoolID adds the poolID to the delete org pool params +func (o *DeleteOrgPoolParams) WithPoolID(poolID string) *DeleteOrgPoolParams { + o.SetPoolID(poolID) + return o +} + +// SetPoolID adds the poolId to the delete org pool params +func (o *DeleteOrgPoolParams) SetPoolID(poolID string) { + o.PoolID = poolID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteOrgPoolParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param orgID + if err := r.SetPathParam("orgID", o.OrgID); err != nil { + return err + } + + // path param poolID + if err := r.SetPathParam("poolID", o.PoolID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/organizations/delete_org_pool_responses.go b/client/organizations/delete_org_pool_responses.go new file mode 100644 index 00000000..82bde7bc --- /dev/null +++ b/client/organizations/delete_org_pool_responses.go @@ -0,0 +1,103 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// DeleteOrgPoolReader is a Reader for the DeleteOrgPool structure. +type DeleteOrgPoolReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteOrgPoolReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + result := NewDeleteOrgPoolDefault(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 +} + +// NewDeleteOrgPoolDefault creates a DeleteOrgPoolDefault with default headers values +func NewDeleteOrgPoolDefault(code int) *DeleteOrgPoolDefault { + return &DeleteOrgPoolDefault{ + _statusCode: code, + } +} + +/* +DeleteOrgPoolDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type DeleteOrgPoolDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this delete org pool default response has a 2xx status code +func (o *DeleteOrgPoolDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete org pool default response has a 3xx status code +func (o *DeleteOrgPoolDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete org pool default response has a 4xx status code +func (o *DeleteOrgPoolDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete org pool default response has a 5xx status code +func (o *DeleteOrgPoolDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete org pool default response a status code equal to that given +func (o *DeleteOrgPoolDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the delete org pool default response +func (o *DeleteOrgPoolDefault) Code() int { + return o._statusCode +} + +func (o *DeleteOrgPoolDefault) Error() string { + return fmt.Sprintf("[DELETE /organizations/{orgID}/pools/{poolID}][%d] DeleteOrgPool default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteOrgPoolDefault) String() string { + return fmt.Sprintf("[DELETE /organizations/{orgID}/pools/{poolID}][%d] DeleteOrgPool default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteOrgPoolDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *DeleteOrgPoolDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/organizations/delete_org_responses.go b/client/organizations/delete_org_responses.go new file mode 100644 index 00000000..11e5ea2a --- /dev/null +++ b/client/organizations/delete_org_responses.go @@ -0,0 +1,103 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// DeleteOrgReader is a Reader for the DeleteOrg structure. +type DeleteOrgReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteOrgReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + result := NewDeleteOrgDefault(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 +} + +// NewDeleteOrgDefault creates a DeleteOrgDefault with default headers values +func NewDeleteOrgDefault(code int) *DeleteOrgDefault { + return &DeleteOrgDefault{ + _statusCode: code, + } +} + +/* +DeleteOrgDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type DeleteOrgDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this delete org default response has a 2xx status code +func (o *DeleteOrgDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete org default response has a 3xx status code +func (o *DeleteOrgDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete org default response has a 4xx status code +func (o *DeleteOrgDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete org default response has a 5xx status code +func (o *DeleteOrgDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete org default response a status code equal to that given +func (o *DeleteOrgDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the delete org default response +func (o *DeleteOrgDefault) Code() int { + return o._statusCode +} + +func (o *DeleteOrgDefault) Error() string { + return fmt.Sprintf("[DELETE /organizations/{orgID}][%d] DeleteOrg default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteOrgDefault) String() string { + return fmt.Sprintf("[DELETE /organizations/{orgID}][%d] DeleteOrg default %+v", o._statusCode, o.Payload) +} + +func (o *DeleteOrgDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *DeleteOrgDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/organizations/get_org_parameters.go b/client/organizations/get_org_parameters.go new file mode 100644 index 00000000..b5bab9c0 --- /dev/null +++ b/client/organizations/get_org_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// NewGetOrgParams creates a new GetOrgParams 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 NewGetOrgParams() *GetOrgParams { + return &GetOrgParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetOrgParamsWithTimeout creates a new GetOrgParams object +// with the ability to set a timeout on a request. +func NewGetOrgParamsWithTimeout(timeout time.Duration) *GetOrgParams { + return &GetOrgParams{ + timeout: timeout, + } +} + +// NewGetOrgParamsWithContext creates a new GetOrgParams object +// with the ability to set a context for a request. +func NewGetOrgParamsWithContext(ctx context.Context) *GetOrgParams { + return &GetOrgParams{ + Context: ctx, + } +} + +// NewGetOrgParamsWithHTTPClient creates a new GetOrgParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetOrgParamsWithHTTPClient(client *http.Client) *GetOrgParams { + return &GetOrgParams{ + HTTPClient: client, + } +} + +/* +GetOrgParams contains all the parameters to send to the API endpoint + + for the get org operation. + + Typically these are written to a http.Request. +*/ +type GetOrgParams struct { + + /* OrgID. + + ID of the organization to fetch. + */ + OrgID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get org params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetOrgParams) WithDefaults() *GetOrgParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get org params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetOrgParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get org params +func (o *GetOrgParams) WithTimeout(timeout time.Duration) *GetOrgParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get org params +func (o *GetOrgParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get org params +func (o *GetOrgParams) WithContext(ctx context.Context) *GetOrgParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get org params +func (o *GetOrgParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get org params +func (o *GetOrgParams) WithHTTPClient(client *http.Client) *GetOrgParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get org params +func (o *GetOrgParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithOrgID adds the orgID to the get org params +func (o *GetOrgParams) WithOrgID(orgID string) *GetOrgParams { + o.SetOrgID(orgID) + return o +} + +// SetOrgID adds the orgId to the get org params +func (o *GetOrgParams) SetOrgID(orgID string) { + o.OrgID = orgID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetOrgParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param orgID + if err := r.SetPathParam("orgID", o.OrgID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/organizations/get_org_pool_parameters.go b/client/organizations/get_org_pool_parameters.go new file mode 100644 index 00000000..dd2dc817 --- /dev/null +++ b/client/organizations/get_org_pool_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// NewGetOrgPoolParams creates a new GetOrgPoolParams 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 NewGetOrgPoolParams() *GetOrgPoolParams { + return &GetOrgPoolParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetOrgPoolParamsWithTimeout creates a new GetOrgPoolParams object +// with the ability to set a timeout on a request. +func NewGetOrgPoolParamsWithTimeout(timeout time.Duration) *GetOrgPoolParams { + return &GetOrgPoolParams{ + timeout: timeout, + } +} + +// NewGetOrgPoolParamsWithContext creates a new GetOrgPoolParams object +// with the ability to set a context for a request. +func NewGetOrgPoolParamsWithContext(ctx context.Context) *GetOrgPoolParams { + return &GetOrgPoolParams{ + Context: ctx, + } +} + +// NewGetOrgPoolParamsWithHTTPClient creates a new GetOrgPoolParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetOrgPoolParamsWithHTTPClient(client *http.Client) *GetOrgPoolParams { + return &GetOrgPoolParams{ + HTTPClient: client, + } +} + +/* +GetOrgPoolParams contains all the parameters to send to the API endpoint + + for the get org pool operation. + + Typically these are written to a http.Request. +*/ +type GetOrgPoolParams struct { + + /* OrgID. + + Organization ID. + */ + OrgID string + + /* PoolID. + + Pool ID. + */ + PoolID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get org pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetOrgPoolParams) WithDefaults() *GetOrgPoolParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get org pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetOrgPoolParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get org pool params +func (o *GetOrgPoolParams) WithTimeout(timeout time.Duration) *GetOrgPoolParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get org pool params +func (o *GetOrgPoolParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get org pool params +func (o *GetOrgPoolParams) WithContext(ctx context.Context) *GetOrgPoolParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get org pool params +func (o *GetOrgPoolParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get org pool params +func (o *GetOrgPoolParams) WithHTTPClient(client *http.Client) *GetOrgPoolParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get org pool params +func (o *GetOrgPoolParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithOrgID adds the orgID to the get org pool params +func (o *GetOrgPoolParams) WithOrgID(orgID string) *GetOrgPoolParams { + o.SetOrgID(orgID) + return o +} + +// SetOrgID adds the orgId to the get org pool params +func (o *GetOrgPoolParams) SetOrgID(orgID string) { + o.OrgID = orgID +} + +// WithPoolID adds the poolID to the get org pool params +func (o *GetOrgPoolParams) WithPoolID(poolID string) *GetOrgPoolParams { + o.SetPoolID(poolID) + return o +} + +// SetPoolID adds the poolId to the get org pool params +func (o *GetOrgPoolParams) SetPoolID(poolID string) { + o.PoolID = poolID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetOrgPoolParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param orgID + if err := r.SetPathParam("orgID", o.OrgID); err != nil { + return err + } + + // path param poolID + if err := r.SetPathParam("poolID", o.PoolID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/organizations/get_org_pool_responses.go b/client/organizations/get_org_pool_responses.go new file mode 100644 index 00000000..0036870f --- /dev/null +++ b/client/organizations/get_org_pool_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// GetOrgPoolReader is a Reader for the GetOrgPool structure. +type GetOrgPoolReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetOrgPoolReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetOrgPoolOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetOrgPoolDefault(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 + } +} + +// NewGetOrgPoolOK creates a GetOrgPoolOK with default headers values +func NewGetOrgPoolOK() *GetOrgPoolOK { + return &GetOrgPoolOK{} +} + +/* +GetOrgPoolOK describes a response with status code 200, with default header values. + +Pool +*/ +type GetOrgPoolOK struct { + Payload garm_params.Pool +} + +// IsSuccess returns true when this get org pool o k response has a 2xx status code +func (o *GetOrgPoolOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get org pool o k response has a 3xx status code +func (o *GetOrgPoolOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get org pool o k response has a 4xx status code +func (o *GetOrgPoolOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get org pool o k response has a 5xx status code +func (o *GetOrgPoolOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get org pool o k response a status code equal to that given +func (o *GetOrgPoolOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get org pool o k response +func (o *GetOrgPoolOK) Code() int { + return 200 +} + +func (o *GetOrgPoolOK) Error() string { + return fmt.Sprintf("[GET /organizations/{orgID}/pools/{poolID}][%d] getOrgPoolOK %+v", 200, o.Payload) +} + +func (o *GetOrgPoolOK) String() string { + return fmt.Sprintf("[GET /organizations/{orgID}/pools/{poolID}][%d] getOrgPoolOK %+v", 200, o.Payload) +} + +func (o *GetOrgPoolOK) GetPayload() garm_params.Pool { + return o.Payload +} + +func (o *GetOrgPoolOK) 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 +} + +// NewGetOrgPoolDefault creates a GetOrgPoolDefault with default headers values +func NewGetOrgPoolDefault(code int) *GetOrgPoolDefault { + return &GetOrgPoolDefault{ + _statusCode: code, + } +} + +/* +GetOrgPoolDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type GetOrgPoolDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this get org pool default response has a 2xx status code +func (o *GetOrgPoolDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get org pool default response has a 3xx status code +func (o *GetOrgPoolDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get org pool default response has a 4xx status code +func (o *GetOrgPoolDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get org pool default response has a 5xx status code +func (o *GetOrgPoolDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get org pool default response a status code equal to that given +func (o *GetOrgPoolDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the get org pool default response +func (o *GetOrgPoolDefault) Code() int { + return o._statusCode +} + +func (o *GetOrgPoolDefault) Error() string { + return fmt.Sprintf("[GET /organizations/{orgID}/pools/{poolID}][%d] GetOrgPool default %+v", o._statusCode, o.Payload) +} + +func (o *GetOrgPoolDefault) String() string { + return fmt.Sprintf("[GET /organizations/{orgID}/pools/{poolID}][%d] GetOrgPool default %+v", o._statusCode, o.Payload) +} + +func (o *GetOrgPoolDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *GetOrgPoolDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/organizations/get_org_responses.go b/client/organizations/get_org_responses.go new file mode 100644 index 00000000..926a088d --- /dev/null +++ b/client/organizations/get_org_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// GetOrgReader is a Reader for the GetOrg structure. +type GetOrgReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetOrgReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetOrgOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetOrgDefault(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 + } +} + +// NewGetOrgOK creates a GetOrgOK with default headers values +func NewGetOrgOK() *GetOrgOK { + return &GetOrgOK{} +} + +/* +GetOrgOK describes a response with status code 200, with default header values. + +Organization +*/ +type GetOrgOK struct { + Payload garm_params.Organization +} + +// IsSuccess returns true when this get org o k response has a 2xx status code +func (o *GetOrgOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get org o k response has a 3xx status code +func (o *GetOrgOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get org o k response has a 4xx status code +func (o *GetOrgOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get org o k response has a 5xx status code +func (o *GetOrgOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get org o k response a status code equal to that given +func (o *GetOrgOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get org o k response +func (o *GetOrgOK) Code() int { + return 200 +} + +func (o *GetOrgOK) Error() string { + return fmt.Sprintf("[GET /organizations/{orgID}][%d] getOrgOK %+v", 200, o.Payload) +} + +func (o *GetOrgOK) String() string { + return fmt.Sprintf("[GET /organizations/{orgID}][%d] getOrgOK %+v", 200, o.Payload) +} + +func (o *GetOrgOK) GetPayload() garm_params.Organization { + return o.Payload +} + +func (o *GetOrgOK) 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 +} + +// NewGetOrgDefault creates a GetOrgDefault with default headers values +func NewGetOrgDefault(code int) *GetOrgDefault { + return &GetOrgDefault{ + _statusCode: code, + } +} + +/* +GetOrgDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type GetOrgDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this get org default response has a 2xx status code +func (o *GetOrgDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get org default response has a 3xx status code +func (o *GetOrgDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get org default response has a 4xx status code +func (o *GetOrgDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get org default response has a 5xx status code +func (o *GetOrgDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get org default response a status code equal to that given +func (o *GetOrgDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the get org default response +func (o *GetOrgDefault) Code() int { + return o._statusCode +} + +func (o *GetOrgDefault) Error() string { + return fmt.Sprintf("[GET /organizations/{orgID}][%d] GetOrg default %+v", o._statusCode, o.Payload) +} + +func (o *GetOrgDefault) String() string { + return fmt.Sprintf("[GET /organizations/{orgID}][%d] GetOrg default %+v", o._statusCode, o.Payload) +} + +func (o *GetOrgDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *GetOrgDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/organizations/list_org_instances_parameters.go b/client/organizations/list_org_instances_parameters.go new file mode 100644 index 00000000..e7167a7e --- /dev/null +++ b/client/organizations/list_org_instances_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// NewListOrgInstancesParams creates a new ListOrgInstancesParams 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 NewListOrgInstancesParams() *ListOrgInstancesParams { + return &ListOrgInstancesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewListOrgInstancesParamsWithTimeout creates a new ListOrgInstancesParams object +// with the ability to set a timeout on a request. +func NewListOrgInstancesParamsWithTimeout(timeout time.Duration) *ListOrgInstancesParams { + return &ListOrgInstancesParams{ + timeout: timeout, + } +} + +// NewListOrgInstancesParamsWithContext creates a new ListOrgInstancesParams object +// with the ability to set a context for a request. +func NewListOrgInstancesParamsWithContext(ctx context.Context) *ListOrgInstancesParams { + return &ListOrgInstancesParams{ + Context: ctx, + } +} + +// NewListOrgInstancesParamsWithHTTPClient creates a new ListOrgInstancesParams object +// with the ability to set a custom HTTPClient for a request. +func NewListOrgInstancesParamsWithHTTPClient(client *http.Client) *ListOrgInstancesParams { + return &ListOrgInstancesParams{ + HTTPClient: client, + } +} + +/* +ListOrgInstancesParams contains all the parameters to send to the API endpoint + + for the list org instances operation. + + Typically these are written to a http.Request. +*/ +type ListOrgInstancesParams struct { + + /* OrgID. + + Organization ID. + */ + OrgID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the list org instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListOrgInstancesParams) WithDefaults() *ListOrgInstancesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the list org instances params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListOrgInstancesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the list org instances params +func (o *ListOrgInstancesParams) WithTimeout(timeout time.Duration) *ListOrgInstancesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list org instances params +func (o *ListOrgInstancesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list org instances params +func (o *ListOrgInstancesParams) WithContext(ctx context.Context) *ListOrgInstancesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list org instances params +func (o *ListOrgInstancesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list org instances params +func (o *ListOrgInstancesParams) WithHTTPClient(client *http.Client) *ListOrgInstancesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list org instances params +func (o *ListOrgInstancesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithOrgID adds the orgID to the list org instances params +func (o *ListOrgInstancesParams) WithOrgID(orgID string) *ListOrgInstancesParams { + o.SetOrgID(orgID) + return o +} + +// SetOrgID adds the orgId to the list org instances params +func (o *ListOrgInstancesParams) SetOrgID(orgID string) { + o.OrgID = orgID +} + +// WriteToRequest writes these params to a swagger request +func (o *ListOrgInstancesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param orgID + if err := r.SetPathParam("orgID", o.OrgID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/organizations/list_org_instances_responses.go b/client/organizations/list_org_instances_responses.go new file mode 100644 index 00000000..1c0f48e0 --- /dev/null +++ b/client/organizations/list_org_instances_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// ListOrgInstancesReader is a Reader for the ListOrgInstances structure. +type ListOrgInstancesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListOrgInstancesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListOrgInstancesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewListOrgInstancesDefault(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 + } +} + +// NewListOrgInstancesOK creates a ListOrgInstancesOK with default headers values +func NewListOrgInstancesOK() *ListOrgInstancesOK { + return &ListOrgInstancesOK{} +} + +/* +ListOrgInstancesOK describes a response with status code 200, with default header values. + +Instances +*/ +type ListOrgInstancesOK struct { + Payload garm_params.Instances +} + +// IsSuccess returns true when this list org instances o k response has a 2xx status code +func (o *ListOrgInstancesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this list org instances o k response has a 3xx status code +func (o *ListOrgInstancesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list org instances o k response has a 4xx status code +func (o *ListOrgInstancesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this list org instances o k response has a 5xx status code +func (o *ListOrgInstancesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this list org instances o k response a status code equal to that given +func (o *ListOrgInstancesOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the list org instances o k response +func (o *ListOrgInstancesOK) Code() int { + return 200 +} + +func (o *ListOrgInstancesOK) Error() string { + return fmt.Sprintf("[GET /organizations/{orgID}/instances][%d] listOrgInstancesOK %+v", 200, o.Payload) +} + +func (o *ListOrgInstancesOK) String() string { + return fmt.Sprintf("[GET /organizations/{orgID}/instances][%d] listOrgInstancesOK %+v", 200, o.Payload) +} + +func (o *ListOrgInstancesOK) GetPayload() garm_params.Instances { + return o.Payload +} + +func (o *ListOrgInstancesOK) 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 +} + +// NewListOrgInstancesDefault creates a ListOrgInstancesDefault with default headers values +func NewListOrgInstancesDefault(code int) *ListOrgInstancesDefault { + return &ListOrgInstancesDefault{ + _statusCode: code, + } +} + +/* +ListOrgInstancesDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type ListOrgInstancesDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this list org instances default response has a 2xx status code +func (o *ListOrgInstancesDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this list org instances default response has a 3xx status code +func (o *ListOrgInstancesDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this list org instances default response has a 4xx status code +func (o *ListOrgInstancesDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this list org instances default response has a 5xx status code +func (o *ListOrgInstancesDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this list org instances default response a status code equal to that given +func (o *ListOrgInstancesDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the list org instances default response +func (o *ListOrgInstancesDefault) Code() int { + return o._statusCode +} + +func (o *ListOrgInstancesDefault) Error() string { + return fmt.Sprintf("[GET /organizations/{orgID}/instances][%d] ListOrgInstances default %+v", o._statusCode, o.Payload) +} + +func (o *ListOrgInstancesDefault) String() string { + return fmt.Sprintf("[GET /organizations/{orgID}/instances][%d] ListOrgInstances default %+v", o._statusCode, o.Payload) +} + +func (o *ListOrgInstancesDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *ListOrgInstancesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/organizations/list_org_pools_parameters.go b/client/organizations/list_org_pools_parameters.go new file mode 100644 index 00000000..15a4284e --- /dev/null +++ b/client/organizations/list_org_pools_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// NewListOrgPoolsParams creates a new ListOrgPoolsParams 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 NewListOrgPoolsParams() *ListOrgPoolsParams { + return &ListOrgPoolsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewListOrgPoolsParamsWithTimeout creates a new ListOrgPoolsParams object +// with the ability to set a timeout on a request. +func NewListOrgPoolsParamsWithTimeout(timeout time.Duration) *ListOrgPoolsParams { + return &ListOrgPoolsParams{ + timeout: timeout, + } +} + +// NewListOrgPoolsParamsWithContext creates a new ListOrgPoolsParams object +// with the ability to set a context for a request. +func NewListOrgPoolsParamsWithContext(ctx context.Context) *ListOrgPoolsParams { + return &ListOrgPoolsParams{ + Context: ctx, + } +} + +// NewListOrgPoolsParamsWithHTTPClient creates a new ListOrgPoolsParams object +// with the ability to set a custom HTTPClient for a request. +func NewListOrgPoolsParamsWithHTTPClient(client *http.Client) *ListOrgPoolsParams { + return &ListOrgPoolsParams{ + HTTPClient: client, + } +} + +/* +ListOrgPoolsParams contains all the parameters to send to the API endpoint + + for the list org pools operation. + + Typically these are written to a http.Request. +*/ +type ListOrgPoolsParams struct { + + /* OrgID. + + Organization ID. + */ + OrgID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the list org pools params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListOrgPoolsParams) WithDefaults() *ListOrgPoolsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the list org pools params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListOrgPoolsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the list org pools params +func (o *ListOrgPoolsParams) WithTimeout(timeout time.Duration) *ListOrgPoolsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list org pools params +func (o *ListOrgPoolsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list org pools params +func (o *ListOrgPoolsParams) WithContext(ctx context.Context) *ListOrgPoolsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list org pools params +func (o *ListOrgPoolsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list org pools params +func (o *ListOrgPoolsParams) WithHTTPClient(client *http.Client) *ListOrgPoolsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list org pools params +func (o *ListOrgPoolsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithOrgID adds the orgID to the list org pools params +func (o *ListOrgPoolsParams) WithOrgID(orgID string) *ListOrgPoolsParams { + o.SetOrgID(orgID) + return o +} + +// SetOrgID adds the orgId to the list org pools params +func (o *ListOrgPoolsParams) SetOrgID(orgID string) { + o.OrgID = orgID +} + +// WriteToRequest writes these params to a swagger request +func (o *ListOrgPoolsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param orgID + if err := r.SetPathParam("orgID", o.OrgID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/organizations/list_org_pools_responses.go b/client/organizations/list_org_pools_responses.go new file mode 100644 index 00000000..b39944fd --- /dev/null +++ b/client/organizations/list_org_pools_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// ListOrgPoolsReader is a Reader for the ListOrgPools structure. +type ListOrgPoolsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListOrgPoolsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListOrgPoolsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewListOrgPoolsDefault(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 + } +} + +// NewListOrgPoolsOK creates a ListOrgPoolsOK with default headers values +func NewListOrgPoolsOK() *ListOrgPoolsOK { + return &ListOrgPoolsOK{} +} + +/* +ListOrgPoolsOK describes a response with status code 200, with default header values. + +Pools +*/ +type ListOrgPoolsOK struct { + Payload garm_params.Pools +} + +// IsSuccess returns true when this list org pools o k response has a 2xx status code +func (o *ListOrgPoolsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this list org pools o k response has a 3xx status code +func (o *ListOrgPoolsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list org pools o k response has a 4xx status code +func (o *ListOrgPoolsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this list org pools o k response has a 5xx status code +func (o *ListOrgPoolsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this list org pools o k response a status code equal to that given +func (o *ListOrgPoolsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the list org pools o k response +func (o *ListOrgPoolsOK) Code() int { + return 200 +} + +func (o *ListOrgPoolsOK) Error() string { + return fmt.Sprintf("[GET /organizations/{orgID}/pools][%d] listOrgPoolsOK %+v", 200, o.Payload) +} + +func (o *ListOrgPoolsOK) String() string { + return fmt.Sprintf("[GET /organizations/{orgID}/pools][%d] listOrgPoolsOK %+v", 200, o.Payload) +} + +func (o *ListOrgPoolsOK) GetPayload() garm_params.Pools { + return o.Payload +} + +func (o *ListOrgPoolsOK) 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 +} + +// NewListOrgPoolsDefault creates a ListOrgPoolsDefault with default headers values +func NewListOrgPoolsDefault(code int) *ListOrgPoolsDefault { + return &ListOrgPoolsDefault{ + _statusCode: code, + } +} + +/* +ListOrgPoolsDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type ListOrgPoolsDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this list org pools default response has a 2xx status code +func (o *ListOrgPoolsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this list org pools default response has a 3xx status code +func (o *ListOrgPoolsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this list org pools default response has a 4xx status code +func (o *ListOrgPoolsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this list org pools default response has a 5xx status code +func (o *ListOrgPoolsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this list org pools default response a status code equal to that given +func (o *ListOrgPoolsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the list org pools default response +func (o *ListOrgPoolsDefault) Code() int { + return o._statusCode +} + +func (o *ListOrgPoolsDefault) Error() string { + return fmt.Sprintf("[GET /organizations/{orgID}/pools][%d] ListOrgPools default %+v", o._statusCode, o.Payload) +} + +func (o *ListOrgPoolsDefault) String() string { + return fmt.Sprintf("[GET /organizations/{orgID}/pools][%d] ListOrgPools default %+v", o._statusCode, o.Payload) +} + +func (o *ListOrgPoolsDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *ListOrgPoolsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/organizations/list_orgs_parameters.go b/client/organizations/list_orgs_parameters.go new file mode 100644 index 00000000..1441722f --- /dev/null +++ b/client/organizations/list_orgs_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// NewListOrgsParams creates a new ListOrgsParams 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 NewListOrgsParams() *ListOrgsParams { + return &ListOrgsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewListOrgsParamsWithTimeout creates a new ListOrgsParams object +// with the ability to set a timeout on a request. +func NewListOrgsParamsWithTimeout(timeout time.Duration) *ListOrgsParams { + return &ListOrgsParams{ + timeout: timeout, + } +} + +// NewListOrgsParamsWithContext creates a new ListOrgsParams object +// with the ability to set a context for a request. +func NewListOrgsParamsWithContext(ctx context.Context) *ListOrgsParams { + return &ListOrgsParams{ + Context: ctx, + } +} + +// NewListOrgsParamsWithHTTPClient creates a new ListOrgsParams object +// with the ability to set a custom HTTPClient for a request. +func NewListOrgsParamsWithHTTPClient(client *http.Client) *ListOrgsParams { + return &ListOrgsParams{ + HTTPClient: client, + } +} + +/* +ListOrgsParams contains all the parameters to send to the API endpoint + + for the list orgs operation. + + Typically these are written to a http.Request. +*/ +type ListOrgsParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the list orgs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListOrgsParams) WithDefaults() *ListOrgsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the list orgs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListOrgsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the list orgs params +func (o *ListOrgsParams) WithTimeout(timeout time.Duration) *ListOrgsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list orgs params +func (o *ListOrgsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list orgs params +func (o *ListOrgsParams) WithContext(ctx context.Context) *ListOrgsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list orgs params +func (o *ListOrgsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list orgs params +func (o *ListOrgsParams) WithHTTPClient(client *http.Client) *ListOrgsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list orgs params +func (o *ListOrgsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListOrgsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/organizations/list_orgs_responses.go b/client/organizations/list_orgs_responses.go new file mode 100644 index 00000000..b29343e3 --- /dev/null +++ b/client/organizations/list_orgs_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// ListOrgsReader is a Reader for the ListOrgs structure. +type ListOrgsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListOrgsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListOrgsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewListOrgsDefault(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 + } +} + +// NewListOrgsOK creates a ListOrgsOK with default headers values +func NewListOrgsOK() *ListOrgsOK { + return &ListOrgsOK{} +} + +/* +ListOrgsOK describes a response with status code 200, with default header values. + +Organizations +*/ +type ListOrgsOK struct { + Payload garm_params.Organizations +} + +// IsSuccess returns true when this list orgs o k response has a 2xx status code +func (o *ListOrgsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this list orgs o k response has a 3xx status code +func (o *ListOrgsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list orgs o k response has a 4xx status code +func (o *ListOrgsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this list orgs o k response has a 5xx status code +func (o *ListOrgsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this list orgs o k response a status code equal to that given +func (o *ListOrgsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the list orgs o k response +func (o *ListOrgsOK) Code() int { + return 200 +} + +func (o *ListOrgsOK) Error() string { + return fmt.Sprintf("[GET /organizations][%d] listOrgsOK %+v", 200, o.Payload) +} + +func (o *ListOrgsOK) String() string { + return fmt.Sprintf("[GET /organizations][%d] listOrgsOK %+v", 200, o.Payload) +} + +func (o *ListOrgsOK) GetPayload() garm_params.Organizations { + return o.Payload +} + +func (o *ListOrgsOK) 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 +} + +// NewListOrgsDefault creates a ListOrgsDefault with default headers values +func NewListOrgsDefault(code int) *ListOrgsDefault { + return &ListOrgsDefault{ + _statusCode: code, + } +} + +/* +ListOrgsDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type ListOrgsDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this list orgs default response has a 2xx status code +func (o *ListOrgsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this list orgs default response has a 3xx status code +func (o *ListOrgsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this list orgs default response has a 4xx status code +func (o *ListOrgsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this list orgs default response has a 5xx status code +func (o *ListOrgsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this list orgs default response a status code equal to that given +func (o *ListOrgsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the list orgs default response +func (o *ListOrgsDefault) Code() int { + return o._statusCode +} + +func (o *ListOrgsDefault) Error() string { + return fmt.Sprintf("[GET /organizations][%d] ListOrgs default %+v", o._statusCode, o.Payload) +} + +func (o *ListOrgsDefault) String() string { + return fmt.Sprintf("[GET /organizations][%d] ListOrgs default %+v", o._statusCode, o.Payload) +} + +func (o *ListOrgsDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *ListOrgsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/organizations/organizations_client.go b/client/organizations/organizations_client.go new file mode 100644 index 00000000..3d75cd86 --- /dev/null +++ b/client/organizations/organizations_client.go @@ -0,0 +1,465 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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 organizations API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for organizations 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 { + CreateOrg(params *CreateOrgParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateOrgOK, error) + + CreateOrgPool(params *CreateOrgPoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateOrgPoolOK, error) + + DeleteOrg(params *DeleteOrgParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error + + DeleteOrgPool(params *DeleteOrgPoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error + + GetOrg(params *GetOrgParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetOrgOK, error) + + GetOrgPool(params *GetOrgPoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetOrgPoolOK, error) + + ListOrgInstances(params *ListOrgInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListOrgInstancesOK, error) + + ListOrgPools(params *ListOrgPoolsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListOrgPoolsOK, error) + + ListOrgs(params *ListOrgsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListOrgsOK, error) + + UpdateOrg(params *UpdateOrgParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateOrgOK, error) + + UpdateOrgPool(params *UpdateOrgPoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateOrgPoolOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +CreateOrg creates organization with the parameters given +*/ +func (a *Client) CreateOrg(params *CreateOrgParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateOrgOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateOrgParams() + } + op := &runtime.ClientOperation{ + ID: "CreateOrg", + Method: "POST", + PathPattern: "/organizations", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateOrgReader{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.(*CreateOrgOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateOrgDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* +CreateOrgPool creates organization pool with the parameters given +*/ +func (a *Client) CreateOrgPool(params *CreateOrgPoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateOrgPoolOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewCreateOrgPoolParams() + } + op := &runtime.ClientOperation{ + ID: "CreateOrgPool", + Method: "POST", + PathPattern: "/organizations/{orgID}/pools", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &CreateOrgPoolReader{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.(*CreateOrgPoolOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*CreateOrgPoolDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* +DeleteOrg deletes organization by ID +*/ +func (a *Client) DeleteOrg(params *DeleteOrgParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteOrgParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteOrg", + Method: "DELETE", + PathPattern: "/organizations/{orgID}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteOrgReader{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 +} + +/* +DeleteOrgPool deletes organization pool by ID +*/ +func (a *Client) DeleteOrgPool(params *DeleteOrgPoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteOrgPoolParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteOrgPool", + Method: "DELETE", + PathPattern: "/organizations/{orgID}/pools/{poolID}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeleteOrgPoolReader{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 +} + +/* +GetOrg gets organization by ID +*/ +func (a *Client) GetOrg(params *GetOrgParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetOrgOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetOrgParams() + } + op := &runtime.ClientOperation{ + ID: "GetOrg", + Method: "GET", + PathPattern: "/organizations/{orgID}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetOrgReader{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.(*GetOrgOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetOrgDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* +GetOrgPool gets organization pool by ID +*/ +func (a *Client) GetOrgPool(params *GetOrgPoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetOrgPoolOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetOrgPoolParams() + } + op := &runtime.ClientOperation{ + ID: "GetOrgPool", + Method: "GET", + PathPattern: "/organizations/{orgID}/pools/{poolID}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetOrgPoolReader{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.(*GetOrgPoolOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetOrgPoolDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* +ListOrgInstances lists organization instances +*/ +func (a *Client) ListOrgInstances(params *ListOrgInstancesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListOrgInstancesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewListOrgInstancesParams() + } + op := &runtime.ClientOperation{ + ID: "ListOrgInstances", + Method: "GET", + PathPattern: "/organizations/{orgID}/instances", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ListOrgInstancesReader{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.(*ListOrgInstancesOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ListOrgInstancesDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* +ListOrgPools lists organization pools +*/ +func (a *Client) ListOrgPools(params *ListOrgPoolsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListOrgPoolsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewListOrgPoolsParams() + } + op := &runtime.ClientOperation{ + ID: "ListOrgPools", + Method: "GET", + PathPattern: "/organizations/{orgID}/pools", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ListOrgPoolsReader{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.(*ListOrgPoolsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ListOrgPoolsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* +ListOrgs lists organizations +*/ +func (a *Client) ListOrgs(params *ListOrgsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListOrgsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewListOrgsParams() + } + op := &runtime.ClientOperation{ + ID: "ListOrgs", + Method: "GET", + PathPattern: "/organizations", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ListOrgsReader{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.(*ListOrgsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ListOrgsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* +UpdateOrg updates organization with the parameters given +*/ +func (a *Client) UpdateOrg(params *UpdateOrgParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateOrgOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewUpdateOrgParams() + } + op := &runtime.ClientOperation{ + ID: "UpdateOrg", + Method: "PUT", + PathPattern: "/organizations/{orgID}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &UpdateOrgReader{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.(*UpdateOrgOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*UpdateOrgDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* +UpdateOrgPool updates organization pool with the parameters given +*/ +func (a *Client) UpdateOrgPool(params *UpdateOrgPoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateOrgPoolOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewUpdateOrgPoolParams() + } + op := &runtime.ClientOperation{ + ID: "UpdateOrgPool", + Method: "PUT", + PathPattern: "/organizations/{orgID}/pools/{poolID}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &UpdateOrgPoolReader{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.(*UpdateOrgPoolOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*UpdateOrgPoolDefault) + 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 +} diff --git a/client/organizations/update_org_parameters.go b/client/organizations/update_org_parameters.go new file mode 100644 index 00000000..e2e32517 --- /dev/null +++ b/client/organizations/update_org_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// NewUpdateOrgParams creates a new UpdateOrgParams 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 NewUpdateOrgParams() *UpdateOrgParams { + return &UpdateOrgParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewUpdateOrgParamsWithTimeout creates a new UpdateOrgParams object +// with the ability to set a timeout on a request. +func NewUpdateOrgParamsWithTimeout(timeout time.Duration) *UpdateOrgParams { + return &UpdateOrgParams{ + timeout: timeout, + } +} + +// NewUpdateOrgParamsWithContext creates a new UpdateOrgParams object +// with the ability to set a context for a request. +func NewUpdateOrgParamsWithContext(ctx context.Context) *UpdateOrgParams { + return &UpdateOrgParams{ + Context: ctx, + } +} + +// NewUpdateOrgParamsWithHTTPClient creates a new UpdateOrgParams object +// with the ability to set a custom HTTPClient for a request. +func NewUpdateOrgParamsWithHTTPClient(client *http.Client) *UpdateOrgParams { + return &UpdateOrgParams{ + HTTPClient: client, + } +} + +/* +UpdateOrgParams contains all the parameters to send to the API endpoint + + for the update org operation. + + Typically these are written to a http.Request. +*/ +type UpdateOrgParams struct { + + /* Body. + + Parameters used when updating the organization. + */ + Body garm_params.UpdateEntityParams + + /* OrgID. + + ID of the organization to update. + */ + OrgID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the update org params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UpdateOrgParams) WithDefaults() *UpdateOrgParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the update org params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UpdateOrgParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the update org params +func (o *UpdateOrgParams) WithTimeout(timeout time.Duration) *UpdateOrgParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the update org params +func (o *UpdateOrgParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the update org params +func (o *UpdateOrgParams) WithContext(ctx context.Context) *UpdateOrgParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the update org params +func (o *UpdateOrgParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the update org params +func (o *UpdateOrgParams) WithHTTPClient(client *http.Client) *UpdateOrgParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the update org params +func (o *UpdateOrgParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the update org params +func (o *UpdateOrgParams) WithBody(body garm_params.UpdateEntityParams) *UpdateOrgParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the update org params +func (o *UpdateOrgParams) SetBody(body garm_params.UpdateEntityParams) { + o.Body = body +} + +// WithOrgID adds the orgID to the update org params +func (o *UpdateOrgParams) WithOrgID(orgID string) *UpdateOrgParams { + o.SetOrgID(orgID) + return o +} + +// SetOrgID adds the orgId to the update org params +func (o *UpdateOrgParams) SetOrgID(orgID string) { + o.OrgID = orgID +} + +// WriteToRequest writes these params to a swagger request +func (o *UpdateOrgParams) 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 orgID + if err := r.SetPathParam("orgID", o.OrgID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/organizations/update_org_pool_parameters.go b/client/organizations/update_org_pool_parameters.go new file mode 100644 index 00000000..089441e4 --- /dev/null +++ b/client/organizations/update_org_pool_parameters.go @@ -0,0 +1,195 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// NewUpdateOrgPoolParams creates a new UpdateOrgPoolParams 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 NewUpdateOrgPoolParams() *UpdateOrgPoolParams { + return &UpdateOrgPoolParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewUpdateOrgPoolParamsWithTimeout creates a new UpdateOrgPoolParams object +// with the ability to set a timeout on a request. +func NewUpdateOrgPoolParamsWithTimeout(timeout time.Duration) *UpdateOrgPoolParams { + return &UpdateOrgPoolParams{ + timeout: timeout, + } +} + +// NewUpdateOrgPoolParamsWithContext creates a new UpdateOrgPoolParams object +// with the ability to set a context for a request. +func NewUpdateOrgPoolParamsWithContext(ctx context.Context) *UpdateOrgPoolParams { + return &UpdateOrgPoolParams{ + Context: ctx, + } +} + +// NewUpdateOrgPoolParamsWithHTTPClient creates a new UpdateOrgPoolParams object +// with the ability to set a custom HTTPClient for a request. +func NewUpdateOrgPoolParamsWithHTTPClient(client *http.Client) *UpdateOrgPoolParams { + return &UpdateOrgPoolParams{ + HTTPClient: client, + } +} + +/* +UpdateOrgPoolParams contains all the parameters to send to the API endpoint + + for the update org pool operation. + + Typically these are written to a http.Request. +*/ +type UpdateOrgPoolParams struct { + + /* Body. + + Parameters used when updating the organization pool. + */ + Body garm_params.UpdatePoolParams + + /* OrgID. + + Organization ID. + */ + OrgID string + + /* PoolID. + + ID of the organization pool to update. + */ + PoolID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the update org pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UpdateOrgPoolParams) WithDefaults() *UpdateOrgPoolParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the update org pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UpdateOrgPoolParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the update org pool params +func (o *UpdateOrgPoolParams) WithTimeout(timeout time.Duration) *UpdateOrgPoolParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the update org pool params +func (o *UpdateOrgPoolParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the update org pool params +func (o *UpdateOrgPoolParams) WithContext(ctx context.Context) *UpdateOrgPoolParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the update org pool params +func (o *UpdateOrgPoolParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the update org pool params +func (o *UpdateOrgPoolParams) WithHTTPClient(client *http.Client) *UpdateOrgPoolParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the update org pool params +func (o *UpdateOrgPoolParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the update org pool params +func (o *UpdateOrgPoolParams) WithBody(body garm_params.UpdatePoolParams) *UpdateOrgPoolParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the update org pool params +func (o *UpdateOrgPoolParams) SetBody(body garm_params.UpdatePoolParams) { + o.Body = body +} + +// WithOrgID adds the orgID to the update org pool params +func (o *UpdateOrgPoolParams) WithOrgID(orgID string) *UpdateOrgPoolParams { + o.SetOrgID(orgID) + return o +} + +// SetOrgID adds the orgId to the update org pool params +func (o *UpdateOrgPoolParams) SetOrgID(orgID string) { + o.OrgID = orgID +} + +// WithPoolID adds the poolID to the update org pool params +func (o *UpdateOrgPoolParams) WithPoolID(poolID string) *UpdateOrgPoolParams { + o.SetPoolID(poolID) + return o +} + +// SetPoolID adds the poolId to the update org pool params +func (o *UpdateOrgPoolParams) SetPoolID(poolID string) { + o.PoolID = poolID +} + +// WriteToRequest writes these params to a swagger request +func (o *UpdateOrgPoolParams) 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 orgID + if err := r.SetPathParam("orgID", o.OrgID); err != nil { + return err + } + + // path param poolID + if err := r.SetPathParam("poolID", o.PoolID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/organizations/update_org_pool_responses.go b/client/organizations/update_org_pool_responses.go new file mode 100644 index 00000000..761195aa --- /dev/null +++ b/client/organizations/update_org_pool_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// UpdateOrgPoolReader is a Reader for the UpdateOrgPool structure. +type UpdateOrgPoolReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UpdateOrgPoolReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUpdateOrgPoolOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewUpdateOrgPoolDefault(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 + } +} + +// NewUpdateOrgPoolOK creates a UpdateOrgPoolOK with default headers values +func NewUpdateOrgPoolOK() *UpdateOrgPoolOK { + return &UpdateOrgPoolOK{} +} + +/* +UpdateOrgPoolOK describes a response with status code 200, with default header values. + +Pool +*/ +type UpdateOrgPoolOK struct { + Payload garm_params.Pool +} + +// IsSuccess returns true when this update org pool o k response has a 2xx status code +func (o *UpdateOrgPoolOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this update org pool o k response has a 3xx status code +func (o *UpdateOrgPoolOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this update org pool o k response has a 4xx status code +func (o *UpdateOrgPoolOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this update org pool o k response has a 5xx status code +func (o *UpdateOrgPoolOK) IsServerError() bool { + return false +} + +// IsCode returns true when this update org pool o k response a status code equal to that given +func (o *UpdateOrgPoolOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the update org pool o k response +func (o *UpdateOrgPoolOK) Code() int { + return 200 +} + +func (o *UpdateOrgPoolOK) Error() string { + return fmt.Sprintf("[PUT /organizations/{orgID}/pools/{poolID}][%d] updateOrgPoolOK %+v", 200, o.Payload) +} + +func (o *UpdateOrgPoolOK) String() string { + return fmt.Sprintf("[PUT /organizations/{orgID}/pools/{poolID}][%d] updateOrgPoolOK %+v", 200, o.Payload) +} + +func (o *UpdateOrgPoolOK) GetPayload() garm_params.Pool { + return o.Payload +} + +func (o *UpdateOrgPoolOK) 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 +} + +// NewUpdateOrgPoolDefault creates a UpdateOrgPoolDefault with default headers values +func NewUpdateOrgPoolDefault(code int) *UpdateOrgPoolDefault { + return &UpdateOrgPoolDefault{ + _statusCode: code, + } +} + +/* +UpdateOrgPoolDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type UpdateOrgPoolDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this update org pool default response has a 2xx status code +func (o *UpdateOrgPoolDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this update org pool default response has a 3xx status code +func (o *UpdateOrgPoolDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this update org pool default response has a 4xx status code +func (o *UpdateOrgPoolDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this update org pool default response has a 5xx status code +func (o *UpdateOrgPoolDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this update org pool default response a status code equal to that given +func (o *UpdateOrgPoolDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the update org pool default response +func (o *UpdateOrgPoolDefault) Code() int { + return o._statusCode +} + +func (o *UpdateOrgPoolDefault) Error() string { + return fmt.Sprintf("[PUT /organizations/{orgID}/pools/{poolID}][%d] UpdateOrgPool default %+v", o._statusCode, o.Payload) +} + +func (o *UpdateOrgPoolDefault) String() string { + return fmt.Sprintf("[PUT /organizations/{orgID}/pools/{poolID}][%d] UpdateOrgPool default %+v", o._statusCode, o.Payload) +} + +func (o *UpdateOrgPoolDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *UpdateOrgPoolDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/organizations/update_org_responses.go b/client/organizations/update_org_responses.go new file mode 100644 index 00000000..2275a545 --- /dev/null +++ b/client/organizations/update_org_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package organizations + +// 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" +) + +// UpdateOrgReader is a Reader for the UpdateOrg structure. +type UpdateOrgReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UpdateOrgReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUpdateOrgOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewUpdateOrgDefault(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 + } +} + +// NewUpdateOrgOK creates a UpdateOrgOK with default headers values +func NewUpdateOrgOK() *UpdateOrgOK { + return &UpdateOrgOK{} +} + +/* +UpdateOrgOK describes a response with status code 200, with default header values. + +Organization +*/ +type UpdateOrgOK struct { + Payload garm_params.Organization +} + +// IsSuccess returns true when this update org o k response has a 2xx status code +func (o *UpdateOrgOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this update org o k response has a 3xx status code +func (o *UpdateOrgOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this update org o k response has a 4xx status code +func (o *UpdateOrgOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this update org o k response has a 5xx status code +func (o *UpdateOrgOK) IsServerError() bool { + return false +} + +// IsCode returns true when this update org o k response a status code equal to that given +func (o *UpdateOrgOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the update org o k response +func (o *UpdateOrgOK) Code() int { + return 200 +} + +func (o *UpdateOrgOK) Error() string { + return fmt.Sprintf("[PUT /organizations/{orgID}][%d] updateOrgOK %+v", 200, o.Payload) +} + +func (o *UpdateOrgOK) String() string { + return fmt.Sprintf("[PUT /organizations/{orgID}][%d] updateOrgOK %+v", 200, o.Payload) +} + +func (o *UpdateOrgOK) GetPayload() garm_params.Organization { + return o.Payload +} + +func (o *UpdateOrgOK) 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 +} + +// NewUpdateOrgDefault creates a UpdateOrgDefault with default headers values +func NewUpdateOrgDefault(code int) *UpdateOrgDefault { + return &UpdateOrgDefault{ + _statusCode: code, + } +} + +/* +UpdateOrgDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type UpdateOrgDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this update org default response has a 2xx status code +func (o *UpdateOrgDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this update org default response has a 3xx status code +func (o *UpdateOrgDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this update org default response has a 4xx status code +func (o *UpdateOrgDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this update org default response has a 5xx status code +func (o *UpdateOrgDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this update org default response a status code equal to that given +func (o *UpdateOrgDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the update org default response +func (o *UpdateOrgDefault) Code() int { + return o._statusCode +} + +func (o *UpdateOrgDefault) Error() string { + return fmt.Sprintf("[PUT /organizations/{orgID}][%d] UpdateOrg default %+v", o._statusCode, o.Payload) +} + +func (o *UpdateOrgDefault) String() string { + return fmt.Sprintf("[PUT /organizations/{orgID}][%d] UpdateOrg default %+v", o._statusCode, o.Payload) +} + +func (o *UpdateOrgDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *UpdateOrgDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/pools/delete_pool_parameters.go b/client/pools/delete_pool_parameters.go new file mode 100644 index 00000000..4524703d --- /dev/null +++ b/client/pools/delete_pool_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package pools + +// 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" +) + +// NewDeletePoolParams creates a new DeletePoolParams 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 NewDeletePoolParams() *DeletePoolParams { + return &DeletePoolParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeletePoolParamsWithTimeout creates a new DeletePoolParams object +// with the ability to set a timeout on a request. +func NewDeletePoolParamsWithTimeout(timeout time.Duration) *DeletePoolParams { + return &DeletePoolParams{ + timeout: timeout, + } +} + +// NewDeletePoolParamsWithContext creates a new DeletePoolParams object +// with the ability to set a context for a request. +func NewDeletePoolParamsWithContext(ctx context.Context) *DeletePoolParams { + return &DeletePoolParams{ + Context: ctx, + } +} + +// NewDeletePoolParamsWithHTTPClient creates a new DeletePoolParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeletePoolParamsWithHTTPClient(client *http.Client) *DeletePoolParams { + return &DeletePoolParams{ + HTTPClient: client, + } +} + +/* +DeletePoolParams contains all the parameters to send to the API endpoint + + for the delete pool operation. + + Typically these are written to a http.Request. +*/ +type DeletePoolParams struct { + + /* PoolID. + + ID of the pool to delete. + */ + PoolID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeletePoolParams) WithDefaults() *DeletePoolParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeletePoolParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete pool params +func (o *DeletePoolParams) WithTimeout(timeout time.Duration) *DeletePoolParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete pool params +func (o *DeletePoolParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete pool params +func (o *DeletePoolParams) WithContext(ctx context.Context) *DeletePoolParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete pool params +func (o *DeletePoolParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete pool params +func (o *DeletePoolParams) WithHTTPClient(client *http.Client) *DeletePoolParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete pool params +func (o *DeletePoolParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithPoolID adds the poolID to the delete pool params +func (o *DeletePoolParams) WithPoolID(poolID string) *DeletePoolParams { + o.SetPoolID(poolID) + return o +} + +// SetPoolID adds the poolId to the delete pool params +func (o *DeletePoolParams) SetPoolID(poolID string) { + o.PoolID = poolID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeletePoolParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param poolID + if err := r.SetPathParam("poolID", o.PoolID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/pools/delete_pool_responses.go b/client/pools/delete_pool_responses.go new file mode 100644 index 00000000..a556eaef --- /dev/null +++ b/client/pools/delete_pool_responses.go @@ -0,0 +1,103 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package pools + +// 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" +) + +// DeletePoolReader is a Reader for the DeletePool structure. +type DeletePoolReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeletePoolReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + result := NewDeletePoolDefault(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 +} + +// NewDeletePoolDefault creates a DeletePoolDefault with default headers values +func NewDeletePoolDefault(code int) *DeletePoolDefault { + return &DeletePoolDefault{ + _statusCode: code, + } +} + +/* +DeletePoolDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type DeletePoolDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this delete pool default response has a 2xx status code +func (o *DeletePoolDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this delete pool default response has a 3xx status code +func (o *DeletePoolDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this delete pool default response has a 4xx status code +func (o *DeletePoolDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this delete pool default response has a 5xx status code +func (o *DeletePoolDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this delete pool default response a status code equal to that given +func (o *DeletePoolDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the delete pool default response +func (o *DeletePoolDefault) Code() int { + return o._statusCode +} + +func (o *DeletePoolDefault) Error() string { + return fmt.Sprintf("[DELETE /pools/{poolID}][%d] DeletePool default %+v", o._statusCode, o.Payload) +} + +func (o *DeletePoolDefault) String() string { + return fmt.Sprintf("[DELETE /pools/{poolID}][%d] DeletePool default %+v", o._statusCode, o.Payload) +} + +func (o *DeletePoolDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *DeletePoolDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/pools/get_pool_parameters.go b/client/pools/get_pool_parameters.go new file mode 100644 index 00000000..c4871e02 --- /dev/null +++ b/client/pools/get_pool_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package pools + +// 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" +) + +// NewGetPoolParams creates a new GetPoolParams 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 NewGetPoolParams() *GetPoolParams { + return &GetPoolParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetPoolParamsWithTimeout creates a new GetPoolParams object +// with the ability to set a timeout on a request. +func NewGetPoolParamsWithTimeout(timeout time.Duration) *GetPoolParams { + return &GetPoolParams{ + timeout: timeout, + } +} + +// NewGetPoolParamsWithContext creates a new GetPoolParams object +// with the ability to set a context for a request. +func NewGetPoolParamsWithContext(ctx context.Context) *GetPoolParams { + return &GetPoolParams{ + Context: ctx, + } +} + +// NewGetPoolParamsWithHTTPClient creates a new GetPoolParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetPoolParamsWithHTTPClient(client *http.Client) *GetPoolParams { + return &GetPoolParams{ + HTTPClient: client, + } +} + +/* +GetPoolParams contains all the parameters to send to the API endpoint + + for the get pool operation. + + Typically these are written to a http.Request. +*/ +type GetPoolParams struct { + + /* PoolID. + + ID of the pool to fetch. + */ + PoolID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetPoolParams) WithDefaults() *GetPoolParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetPoolParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get pool params +func (o *GetPoolParams) WithTimeout(timeout time.Duration) *GetPoolParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get pool params +func (o *GetPoolParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get pool params +func (o *GetPoolParams) WithContext(ctx context.Context) *GetPoolParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get pool params +func (o *GetPoolParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get pool params +func (o *GetPoolParams) WithHTTPClient(client *http.Client) *GetPoolParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get pool params +func (o *GetPoolParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithPoolID adds the poolID to the get pool params +func (o *GetPoolParams) WithPoolID(poolID string) *GetPoolParams { + o.SetPoolID(poolID) + return o +} + +// SetPoolID adds the poolId to the get pool params +func (o *GetPoolParams) SetPoolID(poolID string) { + o.PoolID = poolID +} + +// WriteToRequest writes these params to a swagger request +func (o *GetPoolParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param poolID + if err := r.SetPathParam("poolID", o.PoolID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/pools/get_pool_responses.go b/client/pools/get_pool_responses.go new file mode 100644 index 00000000..22ee22d5 --- /dev/null +++ b/client/pools/get_pool_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package pools + +// 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" +) + +// GetPoolReader is a Reader for the GetPool structure. +type GetPoolReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetPoolReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetPoolOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewGetPoolDefault(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 + } +} + +// NewGetPoolOK creates a GetPoolOK with default headers values +func NewGetPoolOK() *GetPoolOK { + return &GetPoolOK{} +} + +/* +GetPoolOK describes a response with status code 200, with default header values. + +Pool +*/ +type GetPoolOK struct { + Payload garm_params.Pool +} + +// IsSuccess returns true when this get pool o k response has a 2xx status code +func (o *GetPoolOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get pool o k response has a 3xx status code +func (o *GetPoolOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get pool o k response has a 4xx status code +func (o *GetPoolOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get pool o k response has a 5xx status code +func (o *GetPoolOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get pool o k response a status code equal to that given +func (o *GetPoolOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get pool o k response +func (o *GetPoolOK) Code() int { + return 200 +} + +func (o *GetPoolOK) Error() string { + return fmt.Sprintf("[GET /pools/{poolID}][%d] getPoolOK %+v", 200, o.Payload) +} + +func (o *GetPoolOK) String() string { + return fmt.Sprintf("[GET /pools/{poolID}][%d] getPoolOK %+v", 200, o.Payload) +} + +func (o *GetPoolOK) GetPayload() garm_params.Pool { + return o.Payload +} + +func (o *GetPoolOK) 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 +} + +// NewGetPoolDefault creates a GetPoolDefault with default headers values +func NewGetPoolDefault(code int) *GetPoolDefault { + return &GetPoolDefault{ + _statusCode: code, + } +} + +/* +GetPoolDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type GetPoolDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this get pool default response has a 2xx status code +func (o *GetPoolDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this get pool default response has a 3xx status code +func (o *GetPoolDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this get pool default response has a 4xx status code +func (o *GetPoolDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this get pool default response has a 5xx status code +func (o *GetPoolDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this get pool default response a status code equal to that given +func (o *GetPoolDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the get pool default response +func (o *GetPoolDefault) Code() int { + return o._statusCode +} + +func (o *GetPoolDefault) Error() string { + return fmt.Sprintf("[GET /pools/{poolID}][%d] GetPool default %+v", o._statusCode, o.Payload) +} + +func (o *GetPoolDefault) String() string { + return fmt.Sprintf("[GET /pools/{poolID}][%d] GetPool default %+v", o._statusCode, o.Payload) +} + +func (o *GetPoolDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *GetPoolDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/pools/list_pools_parameters.go b/client/pools/list_pools_parameters.go new file mode 100644 index 00000000..361dec69 --- /dev/null +++ b/client/pools/list_pools_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package pools + +// 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" +) + +// NewListPoolsParams creates a new ListPoolsParams 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 NewListPoolsParams() *ListPoolsParams { + return &ListPoolsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewListPoolsParamsWithTimeout creates a new ListPoolsParams object +// with the ability to set a timeout on a request. +func NewListPoolsParamsWithTimeout(timeout time.Duration) *ListPoolsParams { + return &ListPoolsParams{ + timeout: timeout, + } +} + +// NewListPoolsParamsWithContext creates a new ListPoolsParams object +// with the ability to set a context for a request. +func NewListPoolsParamsWithContext(ctx context.Context) *ListPoolsParams { + return &ListPoolsParams{ + Context: ctx, + } +} + +// NewListPoolsParamsWithHTTPClient creates a new ListPoolsParams object +// with the ability to set a custom HTTPClient for a request. +func NewListPoolsParamsWithHTTPClient(client *http.Client) *ListPoolsParams { + return &ListPoolsParams{ + HTTPClient: client, + } +} + +/* +ListPoolsParams contains all the parameters to send to the API endpoint + + for the list pools operation. + + Typically these are written to a http.Request. +*/ +type ListPoolsParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the list pools params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListPoolsParams) WithDefaults() *ListPoolsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the list pools params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListPoolsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the list pools params +func (o *ListPoolsParams) WithTimeout(timeout time.Duration) *ListPoolsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list pools params +func (o *ListPoolsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list pools params +func (o *ListPoolsParams) WithContext(ctx context.Context) *ListPoolsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list pools params +func (o *ListPoolsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list pools params +func (o *ListPoolsParams) WithHTTPClient(client *http.Client) *ListPoolsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list pools params +func (o *ListPoolsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListPoolsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/pools/list_pools_responses.go b/client/pools/list_pools_responses.go new file mode 100644 index 00000000..fa2701d6 --- /dev/null +++ b/client/pools/list_pools_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package pools + +// 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" +) + +// ListPoolsReader is a Reader for the ListPools structure. +type ListPoolsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListPoolsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListPoolsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewListPoolsDefault(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 + } +} + +// NewListPoolsOK creates a ListPoolsOK with default headers values +func NewListPoolsOK() *ListPoolsOK { + return &ListPoolsOK{} +} + +/* +ListPoolsOK describes a response with status code 200, with default header values. + +Pools +*/ +type ListPoolsOK struct { + Payload garm_params.Pools +} + +// IsSuccess returns true when this list pools o k response has a 2xx status code +func (o *ListPoolsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this list pools o k response has a 3xx status code +func (o *ListPoolsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list pools o k response has a 4xx status code +func (o *ListPoolsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this list pools o k response has a 5xx status code +func (o *ListPoolsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this list pools o k response a status code equal to that given +func (o *ListPoolsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the list pools o k response +func (o *ListPoolsOK) Code() int { + return 200 +} + +func (o *ListPoolsOK) Error() string { + return fmt.Sprintf("[GET /pools][%d] listPoolsOK %+v", 200, o.Payload) +} + +func (o *ListPoolsOK) String() string { + return fmt.Sprintf("[GET /pools][%d] listPoolsOK %+v", 200, o.Payload) +} + +func (o *ListPoolsOK) GetPayload() garm_params.Pools { + return o.Payload +} + +func (o *ListPoolsOK) 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 +} + +// NewListPoolsDefault creates a ListPoolsDefault with default headers values +func NewListPoolsDefault(code int) *ListPoolsDefault { + return &ListPoolsDefault{ + _statusCode: code, + } +} + +/* +ListPoolsDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type ListPoolsDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this list pools default response has a 2xx status code +func (o *ListPoolsDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this list pools default response has a 3xx status code +func (o *ListPoolsDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this list pools default response has a 4xx status code +func (o *ListPoolsDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this list pools default response has a 5xx status code +func (o *ListPoolsDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this list pools default response a status code equal to that given +func (o *ListPoolsDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the list pools default response +func (o *ListPoolsDefault) Code() int { + return o._statusCode +} + +func (o *ListPoolsDefault) Error() string { + return fmt.Sprintf("[GET /pools][%d] ListPools default %+v", o._statusCode, o.Payload) +} + +func (o *ListPoolsDefault) String() string { + return fmt.Sprintf("[GET /pools][%d] ListPools default %+v", o._statusCode, o.Payload) +} + +func (o *ListPoolsDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *ListPoolsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/pools/pools_client.go b/client/pools/pools_client.go new file mode 100644 index 00000000..f8b18359 --- /dev/null +++ b/client/pools/pools_client.go @@ -0,0 +1,191 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package pools + +// 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 pools API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for pools 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 { + DeletePool(params *DeletePoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error + + GetPool(params *GetPoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetPoolOK, error) + + ListPools(params *ListPoolsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListPoolsOK, error) + + UpdatePool(params *UpdatePoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdatePoolOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +DeletePool deletes pool by ID +*/ +func (a *Client) DeletePool(params *DeletePoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error { + // TODO: Validate the params before sending + if params == nil { + params = NewDeletePoolParams() + } + op := &runtime.ClientOperation{ + ID: "DeletePool", + Method: "DELETE", + PathPattern: "/pools/{poolID}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &DeletePoolReader{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 +} + +/* +GetPool gets pool by ID +*/ +func (a *Client) GetPool(params *GetPoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetPoolOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetPoolParams() + } + op := &runtime.ClientOperation{ + ID: "GetPool", + Method: "GET", + PathPattern: "/pools/{poolID}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &GetPoolReader{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.(*GetPoolOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*GetPoolDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* +ListPools lists all pools +*/ +func (a *Client) ListPools(params *ListPoolsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListPoolsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewListPoolsParams() + } + op := &runtime.ClientOperation{ + ID: "ListPools", + Method: "GET", + PathPattern: "/pools", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ListPoolsReader{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.(*ListPoolsOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*ListPoolsDefault) + return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) +} + +/* +UpdatePool updates pool by ID +*/ +func (a *Client) UpdatePool(params *UpdatePoolParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdatePoolOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewUpdatePoolParams() + } + op := &runtime.ClientOperation{ + ID: "UpdatePool", + Method: "PUT", + PathPattern: "/pools/{poolID}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &UpdatePoolReader{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.(*UpdatePoolOK) + if ok { + return success, nil + } + // unexpected success response + unexpectedSuccess := result.(*UpdatePoolDefault) + 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 +} diff --git a/client/pools/update_pool_parameters.go b/client/pools/update_pool_parameters.go new file mode 100644 index 00000000..75bf5c96 --- /dev/null +++ b/client/pools/update_pool_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package pools + +// 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" +) + +// NewUpdatePoolParams creates a new UpdatePoolParams 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 NewUpdatePoolParams() *UpdatePoolParams { + return &UpdatePoolParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewUpdatePoolParamsWithTimeout creates a new UpdatePoolParams object +// with the ability to set a timeout on a request. +func NewUpdatePoolParamsWithTimeout(timeout time.Duration) *UpdatePoolParams { + return &UpdatePoolParams{ + timeout: timeout, + } +} + +// NewUpdatePoolParamsWithContext creates a new UpdatePoolParams object +// with the ability to set a context for a request. +func NewUpdatePoolParamsWithContext(ctx context.Context) *UpdatePoolParams { + return &UpdatePoolParams{ + Context: ctx, + } +} + +// NewUpdatePoolParamsWithHTTPClient creates a new UpdatePoolParams object +// with the ability to set a custom HTTPClient for a request. +func NewUpdatePoolParamsWithHTTPClient(client *http.Client) *UpdatePoolParams { + return &UpdatePoolParams{ + HTTPClient: client, + } +} + +/* +UpdatePoolParams contains all the parameters to send to the API endpoint + + for the update pool operation. + + Typically these are written to a http.Request. +*/ +type UpdatePoolParams struct { + + /* Body. + + Parameters to update the pool with. + */ + Body garm_params.UpdatePoolParams + + /* PoolID. + + ID of the pool to update. + */ + PoolID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the update pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UpdatePoolParams) WithDefaults() *UpdatePoolParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the update pool params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *UpdatePoolParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the update pool params +func (o *UpdatePoolParams) WithTimeout(timeout time.Duration) *UpdatePoolParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the update pool params +func (o *UpdatePoolParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the update pool params +func (o *UpdatePoolParams) WithContext(ctx context.Context) *UpdatePoolParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the update pool params +func (o *UpdatePoolParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the update pool params +func (o *UpdatePoolParams) WithHTTPClient(client *http.Client) *UpdatePoolParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the update pool params +func (o *UpdatePoolParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBody adds the body to the update pool params +func (o *UpdatePoolParams) WithBody(body garm_params.UpdatePoolParams) *UpdatePoolParams { + o.SetBody(body) + return o +} + +// SetBody adds the body to the update pool params +func (o *UpdatePoolParams) SetBody(body garm_params.UpdatePoolParams) { + o.Body = body +} + +// WithPoolID adds the poolID to the update pool params +func (o *UpdatePoolParams) WithPoolID(poolID string) *UpdatePoolParams { + o.SetPoolID(poolID) + return o +} + +// SetPoolID adds the poolId to the update pool params +func (o *UpdatePoolParams) SetPoolID(poolID string) { + o.PoolID = poolID +} + +// WriteToRequest writes these params to a swagger request +func (o *UpdatePoolParams) 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 poolID + if err := r.SetPathParam("poolID", o.PoolID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/pools/update_pool_responses.go b/client/pools/update_pool_responses.go new file mode 100644 index 00000000..62e83a95 --- /dev/null +++ b/client/pools/update_pool_responses.go @@ -0,0 +1,179 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package pools + +// 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" +) + +// UpdatePoolReader is a Reader for the UpdatePool structure. +type UpdatePoolReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UpdatePoolReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUpdatePoolOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + default: + result := NewUpdatePoolDefault(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 + } +} + +// NewUpdatePoolOK creates a UpdatePoolOK with default headers values +func NewUpdatePoolOK() *UpdatePoolOK { + return &UpdatePoolOK{} +} + +/* +UpdatePoolOK describes a response with status code 200, with default header values. + +Pool +*/ +type UpdatePoolOK struct { + Payload garm_params.Pool +} + +// IsSuccess returns true when this update pool o k response has a 2xx status code +func (o *UpdatePoolOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this update pool o k response has a 3xx status code +func (o *UpdatePoolOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this update pool o k response has a 4xx status code +func (o *UpdatePoolOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this update pool o k response has a 5xx status code +func (o *UpdatePoolOK) IsServerError() bool { + return false +} + +// IsCode returns true when this update pool o k response a status code equal to that given +func (o *UpdatePoolOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the update pool o k response +func (o *UpdatePoolOK) Code() int { + return 200 +} + +func (o *UpdatePoolOK) Error() string { + return fmt.Sprintf("[PUT /pools/{poolID}][%d] updatePoolOK %+v", 200, o.Payload) +} + +func (o *UpdatePoolOK) String() string { + return fmt.Sprintf("[PUT /pools/{poolID}][%d] updatePoolOK %+v", 200, o.Payload) +} + +func (o *UpdatePoolOK) GetPayload() garm_params.Pool { + return o.Payload +} + +func (o *UpdatePoolOK) 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 +} + +// NewUpdatePoolDefault creates a UpdatePoolDefault with default headers values +func NewUpdatePoolDefault(code int) *UpdatePoolDefault { + return &UpdatePoolDefault{ + _statusCode: code, + } +} + +/* +UpdatePoolDefault describes a response with status code -1, with default header values. + +APIErrorResponse +*/ +type UpdatePoolDefault struct { + _statusCode int + + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this update pool default response has a 2xx status code +func (o *UpdatePoolDefault) IsSuccess() bool { + return o._statusCode/100 == 2 +} + +// IsRedirect returns true when this update pool default response has a 3xx status code +func (o *UpdatePoolDefault) IsRedirect() bool { + return o._statusCode/100 == 3 +} + +// IsClientError returns true when this update pool default response has a 4xx status code +func (o *UpdatePoolDefault) IsClientError() bool { + return o._statusCode/100 == 4 +} + +// IsServerError returns true when this update pool default response has a 5xx status code +func (o *UpdatePoolDefault) IsServerError() bool { + return o._statusCode/100 == 5 +} + +// IsCode returns true when this update pool default response a status code equal to that given +func (o *UpdatePoolDefault) IsCode(code int) bool { + return o._statusCode == code +} + +// Code gets the status code for the update pool default response +func (o *UpdatePoolDefault) Code() int { + return o._statusCode +} + +func (o *UpdatePoolDefault) Error() string { + return fmt.Sprintf("[PUT /pools/{poolID}][%d] UpdatePool default %+v", o._statusCode, o.Payload) +} + +func (o *UpdatePoolDefault) String() string { + return fmt.Sprintf("[PUT /pools/{poolID}][%d] UpdatePool default %+v", o._statusCode, o.Payload) +} + +func (o *UpdatePoolDefault) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *UpdatePoolDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/providers/list_providers_parameters.go b/client/providers/list_providers_parameters.go new file mode 100644 index 00000000..e411b1aa --- /dev/null +++ b/client/providers/list_providers_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package providers + +// 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" +) + +// NewListProvidersParams creates a new ListProvidersParams 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 NewListProvidersParams() *ListProvidersParams { + return &ListProvidersParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewListProvidersParamsWithTimeout creates a new ListProvidersParams object +// with the ability to set a timeout on a request. +func NewListProvidersParamsWithTimeout(timeout time.Duration) *ListProvidersParams { + return &ListProvidersParams{ + timeout: timeout, + } +} + +// NewListProvidersParamsWithContext creates a new ListProvidersParams object +// with the ability to set a context for a request. +func NewListProvidersParamsWithContext(ctx context.Context) *ListProvidersParams { + return &ListProvidersParams{ + Context: ctx, + } +} + +// NewListProvidersParamsWithHTTPClient creates a new ListProvidersParams object +// with the ability to set a custom HTTPClient for a request. +func NewListProvidersParamsWithHTTPClient(client *http.Client) *ListProvidersParams { + return &ListProvidersParams{ + HTTPClient: client, + } +} + +/* +ListProvidersParams contains all the parameters to send to the API endpoint + + for the list providers operation. + + Typically these are written to a http.Request. +*/ +type ListProvidersParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the list providers params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListProvidersParams) WithDefaults() *ListProvidersParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the list providers params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *ListProvidersParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the list providers params +func (o *ListProvidersParams) WithTimeout(timeout time.Duration) *ListProvidersParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list providers params +func (o *ListProvidersParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list providers params +func (o *ListProvidersParams) WithContext(ctx context.Context) *ListProvidersParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list providers params +func (o *ListProvidersParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list providers params +func (o *ListProvidersParams) WithHTTPClient(client *http.Client) *ListProvidersParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list providers params +func (o *ListProvidersParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListProvidersParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/client/providers/list_providers_responses.go b/client/providers/list_providers_responses.go new file mode 100644 index 00000000..e80551d1 --- /dev/null +++ b/client/providers/list_providers_responses.go @@ -0,0 +1,174 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package providers + +// 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" +) + +// ListProvidersReader is a Reader for the ListProviders structure. +type ListProvidersReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListProvidersReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListProvidersOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewListProvidersBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /providers] ListProviders", response, response.Code()) + } +} + +// NewListProvidersOK creates a ListProvidersOK with default headers values +func NewListProvidersOK() *ListProvidersOK { + return &ListProvidersOK{} +} + +/* +ListProvidersOK describes a response with status code 200, with default header values. + +Providers +*/ +type ListProvidersOK struct { + Payload garm_params.Providers +} + +// IsSuccess returns true when this list providers o k response has a 2xx status code +func (o *ListProvidersOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this list providers o k response has a 3xx status code +func (o *ListProvidersOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list providers o k response has a 4xx status code +func (o *ListProvidersOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this list providers o k response has a 5xx status code +func (o *ListProvidersOK) IsServerError() bool { + return false +} + +// IsCode returns true when this list providers o k response a status code equal to that given +func (o *ListProvidersOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the list providers o k response +func (o *ListProvidersOK) Code() int { + return 200 +} + +func (o *ListProvidersOK) Error() string { + return fmt.Sprintf("[GET /providers][%d] listProvidersOK %+v", 200, o.Payload) +} + +func (o *ListProvidersOK) String() string { + return fmt.Sprintf("[GET /providers][%d] listProvidersOK %+v", 200, o.Payload) +} + +func (o *ListProvidersOK) GetPayload() garm_params.Providers { + return o.Payload +} + +func (o *ListProvidersOK) 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 +} + +// NewListProvidersBadRequest creates a ListProvidersBadRequest with default headers values +func NewListProvidersBadRequest() *ListProvidersBadRequest { + return &ListProvidersBadRequest{} +} + +/* +ListProvidersBadRequest describes a response with status code 400, with default header values. + +APIErrorResponse +*/ +type ListProvidersBadRequest struct { + Payload apiserver_params.APIErrorResponse +} + +// IsSuccess returns true when this list providers bad request response has a 2xx status code +func (o *ListProvidersBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this list providers bad request response has a 3xx status code +func (o *ListProvidersBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this list providers bad request response has a 4xx status code +func (o *ListProvidersBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this list providers bad request response has a 5xx status code +func (o *ListProvidersBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this list providers bad request response a status code equal to that given +func (o *ListProvidersBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the list providers bad request response +func (o *ListProvidersBadRequest) Code() int { + return 400 +} + +func (o *ListProvidersBadRequest) Error() string { + return fmt.Sprintf("[GET /providers][%d] listProvidersBadRequest %+v", 400, o.Payload) +} + +func (o *ListProvidersBadRequest) String() string { + return fmt.Sprintf("[GET /providers][%d] listProvidersBadRequest %+v", 400, o.Payload) +} + +func (o *ListProvidersBadRequest) GetPayload() apiserver_params.APIErrorResponse { + return o.Payload +} + +func (o *ListProvidersBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/client/providers/providers_client.go b/client/providers/providers_client.go new file mode 100644 index 00000000..3ddfead8 --- /dev/null +++ b/client/providers/providers_client.go @@ -0,0 +1,80 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package providers + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" +) + +// New creates a new providers API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +/* +Client for providers 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 { + ListProviders(params *ListProvidersParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListProvidersOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +ListProviders lists all providers +*/ +func (a *Client) ListProviders(params *ListProvidersParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListProvidersOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewListProvidersParams() + } + op := &runtime.ClientOperation{ + ID: "ListProviders", + Method: "GET", + PathPattern: "/providers", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http"}, + Params: params, + Reader: &ListProvidersReader{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.(*ListProvidersOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for ListProviders: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/cmd/garm-cli/client/client.go b/cmd/garm-cli/client/client.go deleted file mode 100644 index d9e07c3c..00000000 --- a/cmd/garm-cli/client/client.go +++ /dev/null @@ -1,301 +0,0 @@ -// Copyright 2022 Cloudbase Solutions SRL -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package client - -import ( - "encoding/json" - "fmt" - - apiParams "github.com/cloudbase/garm/apiserver/params" - "github.com/cloudbase/garm/cmd/garm-cli/config" - "github.com/cloudbase/garm/params" - - "github.com/go-resty/resty/v2" - "github.com/pkg/errors" -) - -func NewClient(name string, cfg config.Manager, debug bool) *Client { - cli := resty.New() - if cfg.Token != "" { - cli = cli.SetAuthToken(cfg.Token) - } - cli = cli. - SetHeader("Accept", "application/json"). - SetDebug(debug) - return &Client{ - ManagerName: name, - Config: cfg, - client: cli, - } -} - -type Client struct { - ManagerName string - Config config.Manager - client *resty.Client -} - -func (c *Client) handleError(err error, resp *resty.Response) error { - var ret error - if err != nil { - ret = fmt.Errorf("request returned error: %s", err) - } - - if resp != nil && resp.IsError() { - body := resp.Body() - if len(body) > 0 { - apiErr, decErr := c.decodeAPIError(resp.Body()) - if decErr == nil { - ret = fmt.Errorf("API returned error: %s", apiErr.Details) - } - } - } - return ret -} - -func (c *Client) decodeAPIError(body []byte) (apiParams.APIErrorResponse, error) { - var errDetails apiParams.APIErrorResponse - if err := json.Unmarshal(body, &errDetails); err != nil { - return apiParams.APIErrorResponse{}, fmt.Errorf("invalid response from server, use --debug for more info") - } - - return errDetails, fmt.Errorf("error in API call: %s", errDetails.Details) -} - -func (c *Client) InitManager(url string, param params.NewUserParams) (params.User, error) { - body, err := json.Marshal(param) - if err != nil { - return params.User{}, errors.Wrap(err, "marshaling body") - } - url = fmt.Sprintf("%s/api/v1/first-run/", url) - - var response params.User - resp, err := c.client.R(). - SetBody(body). - SetResult(&response). - Post(url) - if err != nil || resp.IsError() { - apiErr, decErr := c.decodeAPIError(resp.Body()) - if decErr != nil { - return params.User{}, errors.Wrap(decErr, "sending request") - } - return params.User{}, fmt.Errorf("error running init: %s", apiErr.Details) - } - - return response, nil -} - -func (c *Client) Login(url string, param params.PasswordLoginParams) (string, error) { - body, err := json.Marshal(param) - if err != nil { - return "", errors.Wrap(err, "marshaling body") - } - url = fmt.Sprintf("%s/api/v1/auth/login", url) - - var response params.JWTResponse - resp, err := c.client.R(). - SetBody(body). - SetResult(&response). - Post(url) - if err != nil || resp.IsError() { - apiErr, decErr := c.decodeAPIError(resp.Body()) - if decErr != nil { - return "", errors.Wrap(decErr, "sending request") - } - return "", fmt.Errorf("error performing login: %s", apiErr.Details) - } - - return response.Token, nil -} - -func (c *Client) ListCredentials() ([]params.GithubCredentials, error) { - var ghCreds []params.GithubCredentials - url := fmt.Sprintf("%s/api/v1/credentials", c.Config.BaseURL) - resp, err := c.client.R(). - SetResult(&ghCreds). - Get(url) - if err != nil || resp.IsError() { - apiErr, decErr := c.decodeAPIError(resp.Body()) - if decErr != nil { - return nil, errors.Wrap(decErr, "sending request") - } - return nil, fmt.Errorf("error fetching credentials: %s", apiErr.Details) - } - return ghCreds, nil -} - -func (c *Client) ListProviders() ([]params.Provider, error) { - var providers []params.Provider - url := fmt.Sprintf("%s/api/v1/providers", c.Config.BaseURL) - resp, err := c.client.R(). - SetResult(&providers). - Get(url) - if err != nil || resp.IsError() { - apiErr, decErr := c.decodeAPIError(resp.Body()) - if decErr != nil { - return nil, errors.Wrap(decErr, "sending request") - } - return nil, fmt.Errorf("error fetching providers: %s", apiErr.Details) - } - return providers, nil -} - -func (c *Client) GetInstanceByName(instanceName string) (params.Instance, error) { - url := fmt.Sprintf("%s/api/v1/instances/%s", c.Config.BaseURL, instanceName) - - var response params.Instance - resp, err := c.client.R(). - SetResult(&response). - Get(url) - if err != nil || resp.IsError() { - apiErr, decErr := c.decodeAPIError(resp.Body()) - if decErr != nil { - return response, errors.Wrap(decErr, "sending request") - } - return response, fmt.Errorf("error performing login: %s", apiErr.Details) - } - return response, nil -} - -func (c *Client) DeleteRunner(instanceName string) error { - url := fmt.Sprintf("%s/api/v1/instances/%s", c.Config.BaseURL, instanceName) - resp, err := c.client.R(). - Delete(url) - if err != nil || resp.IsError() { - apiErr, decErr := c.decodeAPIError(resp.Body()) - if decErr != nil { - return errors.Wrap(decErr, "sending request") - } - return fmt.Errorf("error deleting runner: %s", apiErr.Details) - } - return nil -} - -func (c *Client) ListAllJobs() ([]params.Job, error) { - url := fmt.Sprintf("%s/api/v1/jobs", c.Config.BaseURL) - - var response []params.Job - resp, err := c.client.R(). - SetResult(&response). - Get(url) - if err != nil || resp.IsError() { - return response, c.handleError(err, resp) - } - return response, nil -} - -func (c *Client) ListPoolInstances(poolID string) ([]params.Instance, error) { - url := fmt.Sprintf("%s/api/v1/pools/%s/instances", c.Config.BaseURL, poolID) - - var response []params.Instance - resp, err := c.client.R(). - SetResult(&response). - Get(url) - if err != nil || resp.IsError() { - apiErr, decErr := c.decodeAPIError(resp.Body()) - if decErr != nil { - return response, errors.Wrap(decErr, "sending request") - } - return response, fmt.Errorf("error performing login: %s", apiErr.Details) - } - return response, nil -} - -func (c *Client) ListAllInstances() ([]params.Instance, error) { - url := fmt.Sprintf("%s/api/v1/instances", c.Config.BaseURL) - - var response []params.Instance - resp, err := c.client.R(). - SetResult(&response). - Get(url) - if err != nil || resp.IsError() { - apiErr, decErr := c.decodeAPIError(resp.Body()) - if decErr != nil { - return response, errors.Wrap(decErr, "sending request") - } - return response, fmt.Errorf("error performing login: %s", apiErr.Details) - } - return response, nil -} - -func (c *Client) GetPoolByID(poolID string) (params.Pool, error) { - url := fmt.Sprintf("%s/api/v1/pools/%s", c.Config.BaseURL, poolID) - - var response params.Pool - resp, err := c.client.R(). - SetResult(&response). - Get(url) - if err != nil || resp.IsError() { - apiErr, decErr := c.decodeAPIError(resp.Body()) - if decErr != nil { - return response, errors.Wrap(decErr, "sending request") - } - return response, fmt.Errorf("error performing login: %s", apiErr.Details) - } - return response, nil -} - -func (c *Client) ListAllPools() ([]params.Pool, error) { - url := fmt.Sprintf("%s/api/v1/pools", c.Config.BaseURL) - - var response []params.Pool - resp, err := c.client.R(). - SetResult(&response). - Get(url) - if err != nil || resp.IsError() { - apiErr, decErr := c.decodeAPIError(resp.Body()) - if decErr != nil { - return response, errors.Wrap(decErr, "sending request") - } - return response, fmt.Errorf("error performing login: %s", apiErr.Details) - } - return response, nil -} - -func (c *Client) DeletePoolByID(poolID string) error { - url := fmt.Sprintf("%s/api/v1/pools/%s", c.Config.BaseURL, poolID) - resp, err := c.client.R(). - Delete(url) - if err != nil || resp.IsError() { - apiErr, decErr := c.decodeAPIError(resp.Body()) - if decErr != nil { - return errors.Wrap(decErr, "sending request") - } - return fmt.Errorf("error deleting pool by ID: %s", apiErr.Details) - } - return nil -} - -func (c *Client) UpdatePoolByID(poolID string, param params.UpdatePoolParams) (params.Pool, error) { - url := fmt.Sprintf("%s/api/v1/pools/%s", c.Config.BaseURL, poolID) - - var response params.Pool - body, err := json.Marshal(param) - if err != nil { - return response, err - } - resp, err := c.client.R(). - SetBody(body). - SetResult(&response). - Put(url) - if err != nil || resp.IsError() { - apiErr, decErr := c.decodeAPIError(resp.Body()) - if decErr != nil { - return response, errors.Wrap(decErr, "sending request") - } - return response, fmt.Errorf("error performing login: %s", apiErr.Details) - } - return response, nil -} diff --git a/cmd/garm-cli/client/enterprises.go b/cmd/garm-cli/client/enterprises.go deleted file mode 100644 index ddb26445..00000000 --- a/cmd/garm-cli/client/enterprises.go +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright 2022 Cloudbase Solutions SRL -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package client - -import ( - "encoding/json" - "fmt" - - "github.com/cloudbase/garm/params" -) - -func (c *Client) ListEnterprises() ([]params.Enterprise, error) { - var enterprises []params.Enterprise - url := fmt.Sprintf("%s/api/v1/enterprises", c.Config.BaseURL) - resp, err := c.client.R(). - SetResult(&enterprises). - Get(url) - if err := c.handleError(err, resp); err != nil { - return nil, err - } - return enterprises, nil -} - -func (c *Client) CreateEnterprise(param params.CreateEnterpriseParams) (params.Enterprise, error) { - var response params.Enterprise - url := fmt.Sprintf("%s/api/v1/enterprises", c.Config.BaseURL) - - body, err := json.Marshal(param) - if err != nil { - return params.Enterprise{}, err - } - resp, err := c.client.R(). - SetBody(body). - SetResult(&response). - Post(url) - if err := c.handleError(err, resp); err != nil { - return params.Enterprise{}, err - } - return response, nil -} - -func (c *Client) UpdateEnterprise(enterpriseID string, param params.UpdateEntityParams) (params.Enterprise, error) { - url := fmt.Sprintf("%s/api/v1/enterprises/%s", c.Config.BaseURL, enterpriseID) - - var response params.Enterprise - body, err := json.Marshal(param) - if err != nil { - return response, err - } - resp, err := c.client.R(). - SetBody(body). - SetResult(&response). - Put(url) - if err := c.handleError(err, resp); err != nil { - return params.Enterprise{}, err - } - return response, nil -} - -func (c *Client) GetEnterprise(enterpriseID string) (params.Enterprise, error) { - var response params.Enterprise - url := fmt.Sprintf("%s/api/v1/enterprises/%s", c.Config.BaseURL, enterpriseID) - resp, err := c.client.R(). - SetResult(&response). - Get(url) - if err := c.handleError(err, resp); err != nil { - return params.Enterprise{}, err - } - return response, nil -} - -func (c *Client) DeleteEnterprise(enterpriseID string) error { - url := fmt.Sprintf("%s/api/v1/enterprises/%s", c.Config.BaseURL, enterpriseID) - resp, err := c.client.R(). - Delete(url) - if err := c.handleError(err, resp); err != nil { - return err - } - return nil -} - -func (c *Client) CreateEnterprisePool(enterpriseID string, param params.CreatePoolParams) (params.Pool, error) { - url := fmt.Sprintf("%s/api/v1/enterprises/%s/pools", c.Config.BaseURL, enterpriseID) - - var response params.Pool - body, err := json.Marshal(param) - if err != nil { - return response, err - } - resp, err := c.client.R(). - SetBody(body). - SetResult(&response). - Post(url) - if err := c.handleError(err, resp); err != nil { - return params.Pool{}, err - } - return response, nil -} - -func (c *Client) ListEnterprisePools(enterpriseID string) ([]params.Pool, error) { - url := fmt.Sprintf("%s/api/v1/enterprises/%s/pools", c.Config.BaseURL, enterpriseID) - - var response []params.Pool - resp, err := c.client.R(). - SetResult(&response). - Get(url) - if err := c.handleError(err, resp); err != nil { - return nil, err - } - return response, nil -} - -func (c *Client) GetEnterprisePool(enterpriseID, poolID string) (params.Pool, error) { - url := fmt.Sprintf("%s/api/v1/enterprises/%s/pools/%s", c.Config.BaseURL, enterpriseID, poolID) - - var response params.Pool - resp, err := c.client.R(). - SetResult(&response). - Get(url) - if err := c.handleError(err, resp); err != nil { - return params.Pool{}, err - } - return response, nil -} - -func (c *Client) DeleteEnterprisePool(enterpriseID, poolID string) error { - url := fmt.Sprintf("%s/api/v1/enterprises/%s/pools/%s", c.Config.BaseURL, enterpriseID, poolID) - - resp, err := c.client.R(). - Delete(url) - - if err := c.handleError(err, resp); err != nil { - return err - } - return nil -} - -func (c *Client) UpdateEnterprisePool(enterpriseID, poolID string, param params.UpdatePoolParams) (params.Pool, error) { - url := fmt.Sprintf("%s/api/v1/enterprises/%s/pools/%s", c.Config.BaseURL, enterpriseID, poolID) - - var response params.Pool - body, err := json.Marshal(param) - if err != nil { - return response, err - } - resp, err := c.client.R(). - SetBody(body). - SetResult(&response). - Put(url) - if err := c.handleError(err, resp); err != nil { - return params.Pool{}, err - } - return response, nil -} - -func (c *Client) ListEnterpriseInstances(enterpriseID string) ([]params.Instance, error) { - url := fmt.Sprintf("%s/api/v1/enterprises/%s/instances", c.Config.BaseURL, enterpriseID) - - var response []params.Instance - resp, err := c.client.R(). - SetResult(&response). - Get(url) - if err := c.handleError(err, resp); err != nil { - return nil, err - } - return response, nil -} diff --git a/cmd/garm-cli/client/organizations.go b/cmd/garm-cli/client/organizations.go deleted file mode 100644 index 59411455..00000000 --- a/cmd/garm-cli/client/organizations.go +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright 2022 Cloudbase Solutions SRL -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package client - -import ( - "encoding/json" - "fmt" - - "github.com/cloudbase/garm/params" -) - -func (c *Client) ListOrganizations() ([]params.Organization, error) { - var orgs []params.Organization - url := fmt.Sprintf("%s/api/v1/organizations", c.Config.BaseURL) - resp, err := c.client.R(). - SetResult(&orgs). - Get(url) - if err := c.handleError(err, resp); err != nil { - return nil, err - } - return orgs, nil -} - -func (c *Client) CreateOrganization(param params.CreateOrgParams) (params.Organization, error) { - var response params.Organization - url := fmt.Sprintf("%s/api/v1/organizations", c.Config.BaseURL) - - body, err := json.Marshal(param) - if err != nil { - return params.Organization{}, err - } - resp, err := c.client.R(). - SetBody(body). - SetResult(&response). - Post(url) - if err := c.handleError(err, resp); err != nil { - return params.Organization{}, err - } - return response, nil -} - -func (c *Client) UpdateOrganization(orgID string, param params.UpdateEntityParams) (params.Organization, error) { - url := fmt.Sprintf("%s/api/v1/organizations/%s", c.Config.BaseURL, orgID) - - var response params.Organization - body, err := json.Marshal(param) - if err != nil { - return response, err - } - resp, err := c.client.R(). - SetBody(body). - SetResult(&response). - Put(url) - if err := c.handleError(err, resp); err != nil { - return params.Organization{}, err - } - return response, nil -} - -func (c *Client) GetOrganization(orgID string) (params.Organization, error) { - var response params.Organization - url := fmt.Sprintf("%s/api/v1/organizations/%s", c.Config.BaseURL, orgID) - resp, err := c.client.R(). - SetResult(&response). - Get(url) - if err := c.handleError(err, resp); err != nil { - return params.Organization{}, err - } - return response, nil -} - -func (c *Client) DeleteOrganization(orgID string) error { - url := fmt.Sprintf("%s/api/v1/organizations/%s", c.Config.BaseURL, orgID) - resp, err := c.client.R(). - Delete(url) - if err := c.handleError(err, resp); err != nil { - return err - } - return nil -} - -func (c *Client) CreateOrgPool(orgID string, param params.CreatePoolParams) (params.Pool, error) { - url := fmt.Sprintf("%s/api/v1/organizations/%s/pools", c.Config.BaseURL, orgID) - - var response params.Pool - body, err := json.Marshal(param) - if err != nil { - return response, err - } - resp, err := c.client.R(). - SetBody(body). - SetResult(&response). - Post(url) - if err := c.handleError(err, resp); err != nil { - return params.Pool{}, err - } - return response, nil -} - -func (c *Client) ListOrgPools(orgID string) ([]params.Pool, error) { - url := fmt.Sprintf("%s/api/v1/organizations/%s/pools", c.Config.BaseURL, orgID) - - var response []params.Pool - resp, err := c.client.R(). - SetResult(&response). - Get(url) - if err := c.handleError(err, resp); err != nil { - return nil, err - } - return response, nil -} - -func (c *Client) GetOrgPool(orgID, poolID string) (params.Pool, error) { - url := fmt.Sprintf("%s/api/v1/organizations/%s/pools/%s", c.Config.BaseURL, orgID, poolID) - - var response params.Pool - resp, err := c.client.R(). - SetResult(&response). - Get(url) - if err := c.handleError(err, resp); err != nil { - return params.Pool{}, err - } - return response, nil -} - -func (c *Client) DeleteOrgPool(orgID, poolID string) error { - url := fmt.Sprintf("%s/api/v1/organizations/%s/pools/%s", c.Config.BaseURL, orgID, poolID) - - resp, err := c.client.R(). - Delete(url) - - if err := c.handleError(err, resp); err != nil { - return err - } - return nil -} - -func (c *Client) UpdateOrgPool(orgID, poolID string, param params.UpdatePoolParams) (params.Pool, error) { - url := fmt.Sprintf("%s/api/v1/organizations/%s/pools/%s", c.Config.BaseURL, orgID, poolID) - - var response params.Pool - body, err := json.Marshal(param) - if err != nil { - return response, err - } - resp, err := c.client.R(). - SetBody(body). - SetResult(&response). - Put(url) - if err := c.handleError(err, resp); err != nil { - return params.Pool{}, err - } - return response, nil -} - -func (c *Client) ListOrgInstances(orgID string) ([]params.Instance, error) { - url := fmt.Sprintf("%s/api/v1/organizations/%s/instances", c.Config.BaseURL, orgID) - - var response []params.Instance - resp, err := c.client.R(). - SetResult(&response). - Get(url) - if err := c.handleError(err, resp); err != nil { - return nil, err - } - return response, nil -} - -func (c *Client) CreateMetricsToken() (string, error) { - url := fmt.Sprintf("%s/api/v1/metrics-token", c.Config.BaseURL) - - type response struct { - Token string `json:"token"` - } - - var t response - resp, err := c.client.R(). - SetResult(&t). - Get(url) - if err := c.handleError(err, resp); err != nil { - return "", err - } - return t.Token, nil -} diff --git a/cmd/garm-cli/client/repositories.go b/cmd/garm-cli/client/repositories.go deleted file mode 100644 index 744e7f81..00000000 --- a/cmd/garm-cli/client/repositories.go +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright 2022 Cloudbase Solutions SRL -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package client - -import ( - "encoding/json" - "fmt" - - "github.com/cloudbase/garm/params" -) - -func (c *Client) ListRepositories() ([]params.Repository, error) { - var repos []params.Repository - url := fmt.Sprintf("%s/api/v1/repositories", c.Config.BaseURL) - resp, err := c.client.R(). - SetResult(&repos). - Get(url) - if err := c.handleError(err, resp); err != nil { - return nil, err - } - return repos, nil -} - -func (c *Client) CreateRepository(param params.CreateRepoParams) (params.Repository, error) { - var response params.Repository - url := fmt.Sprintf("%s/api/v1/repositories", c.Config.BaseURL) - - body, err := json.Marshal(param) - if err != nil { - return params.Repository{}, err - } - resp, err := c.client.R(). - SetBody(body). - SetResult(&response). - Post(url) - if err := c.handleError(err, resp); err != nil { - return params.Repository{}, err - } - return response, nil -} - -func (c *Client) GetRepository(repoID string) (params.Repository, error) { - var response params.Repository - url := fmt.Sprintf("%s/api/v1/repositories/%s", c.Config.BaseURL, repoID) - resp, err := c.client.R(). - SetResult(&response). - Get(url) - if err := c.handleError(err, resp); err != nil { - return params.Repository{}, err - } - return response, nil -} - -func (c *Client) DeleteRepository(repoID string) error { - url := fmt.Sprintf("%s/api/v1/repositories/%s", c.Config.BaseURL, repoID) - resp, err := c.client.R(). - Delete(url) - if err := c.handleError(err, resp); err != nil { - return err - } - return nil -} - -func (c *Client) CreateRepoPool(repoID string, param params.CreatePoolParams) (params.Pool, error) { - url := fmt.Sprintf("%s/api/v1/repositories/%s/pools", c.Config.BaseURL, repoID) - - var response params.Pool - body, err := json.Marshal(param) - if err != nil { - return response, err - } - resp, err := c.client.R(). - SetBody(body). - SetResult(&response). - Post(url) - if err := c.handleError(err, resp); err != nil { - return params.Pool{}, err - } - return response, nil -} - -func (c *Client) ListRepoPools(repoID string) ([]params.Pool, error) { - url := fmt.Sprintf("%s/api/v1/repositories/%s/pools", c.Config.BaseURL, repoID) - - var response []params.Pool - resp, err := c.client.R(). - SetResult(&response). - Get(url) - if err := c.handleError(err, resp); err != nil { - return nil, err - } - return response, nil -} - -func (c *Client) GetRepoPool(repoID, poolID string) (params.Pool, error) { - url := fmt.Sprintf("%s/api/v1/repositories/%s/pools/%s", c.Config.BaseURL, repoID, poolID) - - var response params.Pool - resp, err := c.client.R(). - SetResult(&response). - Get(url) - if err := c.handleError(err, resp); err != nil { - return params.Pool{}, err - } - return response, nil -} - -func (c *Client) DeleteRepoPool(repoID, poolID string) error { - url := fmt.Sprintf("%s/api/v1/repositories/%s/pools/%s", c.Config.BaseURL, repoID, poolID) - - resp, err := c.client.R(). - Delete(url) - - if err := c.handleError(err, resp); err != nil { - return err - } - return nil -} - -func (c *Client) UpdateRepoPool(repoID, poolID string, param params.UpdatePoolParams) (params.Pool, error) { - url := fmt.Sprintf("%s/api/v1/repositories/%s/pools/%s", c.Config.BaseURL, repoID, poolID) - - var response params.Pool - body, err := json.Marshal(param) - if err != nil { - return response, err - } - resp, err := c.client.R(). - SetBody(body). - SetResult(&response). - Put(url) - if err := c.handleError(err, resp); err != nil { - return params.Pool{}, err - } - return response, nil -} - -func (c *Client) UpdateRepo(repoID string, param params.UpdateEntityParams) (params.Repository, error) { - url := fmt.Sprintf("%s/api/v1/repositories/%s", c.Config.BaseURL, repoID) - - var response params.Repository - body, err := json.Marshal(param) - if err != nil { - return response, err - } - resp, err := c.client.R(). - SetBody(body). - SetResult(&response). - Put(url) - if err := c.handleError(err, resp); err != nil { - return params.Repository{}, err - } - return response, nil -} - -func (c *Client) ListRepoInstances(repoID string) ([]params.Instance, error) { - url := fmt.Sprintf("%s/api/v1/repositories/%s/instances", c.Config.BaseURL, repoID) - - var response []params.Instance - resp, err := c.client.R(). - SetResult(&response). - Get(url) - if err := c.handleError(err, resp); err != nil { - return nil, err - } - return response, nil -} diff --git a/cmd/garm-cli/cmd/credentials.go b/cmd/garm-cli/cmd/credentials.go index 6559eeb6..ec73c95f 100644 --- a/cmd/garm-cli/cmd/credentials.go +++ b/cmd/garm-cli/cmd/credentials.go @@ -17,6 +17,7 @@ package cmd import ( "fmt" + apiClientCreds "github.com/cloudbase/garm/client/credentials" "github.com/cloudbase/garm/params" "github.com/jedib0t/go-pretty/v6/table" @@ -50,11 +51,12 @@ func init() { return errNeedsInitError } - creds, err := cli.ListCredentials() + listCredsReq := apiClientCreds.NewListCredentialsParams() + response, err := apiCli.Credentials.ListCredentials(listCredsReq, authToken) if err != nil { return err } - formatGithubCredentials(creds) + formatGithubCredentials(response.Payload) return nil }, }) diff --git a/cmd/garm-cli/cmd/enterprise.go b/cmd/garm-cli/cmd/enterprise.go index a16ee66d..c63e0c44 100644 --- a/cmd/garm-cli/cmd/enterprise.go +++ b/cmd/garm-cli/cmd/enterprise.go @@ -17,6 +17,7 @@ package cmd import ( "fmt" + apiClientEnterprises "github.com/cloudbase/garm/client/enterprises" "github.com/cloudbase/garm/params" "github.com/jedib0t/go-pretty/v6/table" @@ -54,16 +55,17 @@ var enterpriseAddCmd = &cobra.Command{ return errNeedsInitError } - newEnterpriseReq := params.CreateEnterpriseParams{ + newEnterpriseReq := apiClientEnterprises.NewCreateEnterpriseParams() + newEnterpriseReq.Body = params.CreateEnterpriseParams{ Name: enterpriseName, WebhookSecret: enterpriseWebhookSecret, CredentialsName: enterpriseCreds, } - enterprise, err := cli.CreateEnterprise(newEnterpriseReq) + response, err := apiCli.Enterprises.CreateEnterprise(newEnterpriseReq, authToken) if err != nil { return err } - formatOneEnterprise(enterprise) + formatOneEnterprise(response.Payload) return nil }, } @@ -79,11 +81,12 @@ var enterpriseListCmd = &cobra.Command{ return errNeedsInitError } - enterprises, err := cli.ListEnterprises() + listEnterprisesReq := apiClientEnterprises.NewListEnterprisesParams() + response, err := apiCli.Enterprises.ListEnterprises(listEnterprisesReq, authToken) if err != nil { return err } - formatEnterprises(enterprises) + formatEnterprises(response.Payload) return nil }, } @@ -103,11 +106,13 @@ var enterpriseShowCmd = &cobra.Command{ if len(args) > 1 { return fmt.Errorf("too many arguments") } - enterprise, err := cli.GetEnterprise(args[0]) + showEnterpriseReq := apiClientEnterprises.NewGetEnterpriseParams() + showEnterpriseReq.EnterpriseID = args[0] + response, err := apiCli.Enterprises.GetEnterprise(showEnterpriseReq, authToken) if err != nil { return err } - formatOneEnterprise(enterprise) + formatOneEnterprise(response.Payload) return nil }, } @@ -128,7 +133,9 @@ var enterpriseDeleteCmd = &cobra.Command{ if len(args) > 1 { return fmt.Errorf("too many arguments") } - if err := cli.DeleteEnterprise(args[0]); err != nil { + deleteEnterpriseReq := apiClientEnterprises.NewDeleteEnterpriseParams() + deleteEnterpriseReq.EnterpriseID = args[0] + if err := apiCli.Enterprises.DeleteEnterprise(deleteEnterpriseReq, authToken); err != nil { return err } return nil @@ -152,16 +159,17 @@ var enterpriseUpdateCmd = &cobra.Command{ if len(args) > 1 { return fmt.Errorf("too many arguments") } - - enterpriseUpdateReq := params.UpdateEntityParams{ + updateEnterpriseReq := apiClientEnterprises.NewUpdateEnterpriseParams() + updateEnterpriseReq.Body = params.UpdateEntityParams{ WebhookSecret: repoWebhookSecret, CredentialsName: repoCreds, } - enterprise, err := cli.UpdateEnterprise(args[0], enterpriseUpdateReq) + updateEnterpriseReq.EnterpriseID = args[0] + response, err := apiCli.Enterprises.UpdateEnterprise(updateEnterpriseReq, authToken) if err != nil { return err } - formatOneEnterprise(enterprise) + formatOneEnterprise(response.Payload) return nil }, } diff --git a/cmd/garm-cli/cmd/init.go b/cmd/garm-cli/cmd/init.go index 3c879c3f..b85c5a8f 100644 --- a/cmd/garm-cli/cmd/init.go +++ b/cmd/garm-cli/cmd/init.go @@ -22,6 +22,8 @@ import ( "github.com/cloudbase/garm/cmd/garm-cli/config" "github.com/cloudbase/garm/params" + apiClientFirstRun "github.com/cloudbase/garm/client/first_run" + apiClientLogin "github.com/cloudbase/garm/client/login" "github.com/jedib0t/go-pretty/v6/table" "github.com/pkg/errors" "github.com/spf13/cobra" @@ -54,7 +56,8 @@ garm-cli init --name=dev --url=https://runner.example.com --username=admin --pas return err } - newUser := params.NewUserParams{ + newUserReq := apiClientFirstRun.NewFirstRunParams() + newUserReq.Body = params.NewUserParams{ Username: loginUserName, Password: loginPassword, FullName: loginFullName, @@ -62,17 +65,21 @@ garm-cli init --name=dev --url=https://runner.example.com --username=admin --pas } url := strings.TrimSuffix(loginURL, "/") - response, err := cli.InitManager(url, newUser) + + initApiClient(url, "") + + response, err := apiCli.FirstRun.FirstRun(newUserReq, authToken) if err != nil { return errors.Wrap(err, "initializing manager") } - loginParams := params.PasswordLoginParams{ + newLoginParamsReq := apiClientLogin.NewLoginParams() + newLoginParamsReq.Body = params.PasswordLoginParams{ Username: loginUserName, Password: loginPassword, } - token, err := cli.Login(url, loginParams) + token, err := apiCli.Login.Login(newLoginParamsReq, authToken) if err != nil { return errors.Wrap(err, "authenticating") } @@ -80,7 +87,7 @@ garm-cli init --name=dev --url=https://runner.example.com --username=admin --pas cfg.Managers = append(cfg.Managers, config.Manager{ Name: loginProfileName, BaseURL: url, - Token: token, + Token: token.Payload.Token, }) cfg.ActiveManager = loginProfileName @@ -89,7 +96,7 @@ garm-cli init --name=dev --url=https://runner.example.com --username=admin --pas return errors.Wrap(err, "saving config") } - renderUserTable(response) + renderUserTable(response.Payload) return nil }, } diff --git a/cmd/garm-cli/cmd/jobs.go b/cmd/garm-cli/cmd/jobs.go index f64d94b6..36f61e8e 100644 --- a/cmd/garm-cli/cmd/jobs.go +++ b/cmd/garm-cli/cmd/jobs.go @@ -18,6 +18,7 @@ import ( "fmt" "strings" + apiClientJobs "github.com/cloudbase/garm/client/jobs" "github.com/cloudbase/garm/params" "github.com/google/uuid" "github.com/jedib0t/go-pretty/v6/table" @@ -44,11 +45,12 @@ var jobsListCmd = &cobra.Command{ return errNeedsInitError } - jobs, err := cli.ListAllJobs() + listJobsReq := apiClientJobs.NewListJobsParams() + response, err := apiCli.Jobs.ListJobs(listJobsReq, authToken) if err != nil { return err } - formatJobs(jobs) + formatJobs(response.Payload) return nil }, } diff --git a/cmd/garm-cli/cmd/log.go b/cmd/garm-cli/cmd/log.go index 4b7e031c..9e6669ce 100644 --- a/cmd/garm-cli/cmd/log.go +++ b/cmd/garm-cli/cmd/log.go @@ -10,8 +10,8 @@ import ( "os/signal" "time" + "github.com/cloudbase/garm-provider-common/util" apiParams "github.com/cloudbase/garm/apiserver/params" - "github.com/cloudbase/garm/util" "github.com/gorilla/websocket" "github.com/spf13/cobra" diff --git a/cmd/garm-cli/cmd/metrics.go b/cmd/garm-cli/cmd/metrics.go index 4069e3e6..e79d9456 100644 --- a/cmd/garm-cli/cmd/metrics.go +++ b/cmd/garm-cli/cmd/metrics.go @@ -17,6 +17,7 @@ package cmd import ( "fmt" + apiClientMetricToken "github.com/cloudbase/garm/client/metrics_token" "github.com/spf13/cobra" ) @@ -39,11 +40,12 @@ var metricsTokenCreateCmd = &cobra.Command{ return errNeedsInitError } - token, err := cli.CreateMetricsToken() + showMetricsTokenReq := apiClientMetricToken.NewGetMetricsTokenParams() + response, err := apiCli.MetricsToken.GetMetricsToken(showMetricsTokenReq, authToken) if err != nil { return err } - fmt.Println(token) + fmt.Println(response.Payload.Token) return nil }, diff --git a/cmd/garm-cli/cmd/organization.go b/cmd/garm-cli/cmd/organization.go index 1338d3ae..56de989b 100644 --- a/cmd/garm-cli/cmd/organization.go +++ b/cmd/garm-cli/cmd/organization.go @@ -17,6 +17,7 @@ package cmd import ( "fmt" + apiClientOrgs "github.com/cloudbase/garm/client/organizations" "github.com/cloudbase/garm/params" "github.com/jedib0t/go-pretty/v6/table" @@ -54,16 +55,17 @@ var orgAddCmd = &cobra.Command{ return errNeedsInitError } - newOrgReq := params.CreateOrgParams{ + newOrgReq := apiClientOrgs.NewCreateOrgParams() + newOrgReq.Body = params.CreateOrgParams{ Name: orgName, WebhookSecret: orgWebhookSecret, CredentialsName: orgCreds, } - org, err := cli.CreateOrganization(newOrgReq) + response, err := apiCli.Organizations.CreateOrg(newOrgReq, authToken) if err != nil { return err } - formatOneOrganization(org) + formatOneOrganization(response.Payload) return nil }, } @@ -85,16 +87,17 @@ var orgUpdateCmd = &cobra.Command{ if len(args) > 1 { return fmt.Errorf("too many arguments") } - - orgUpdateReq := params.UpdateEntityParams{ + updateOrgReq := apiClientOrgs.NewUpdateOrgParams() + updateOrgReq.Body = params.UpdateEntityParams{ WebhookSecret: repoWebhookSecret, CredentialsName: orgCreds, } - org, err := cli.UpdateOrganization(args[0], orgUpdateReq) + updateOrgReq.OrgID = args[0] + response, err := apiCli.Organizations.UpdateOrg(updateOrgReq, authToken) if err != nil { return err } - formatOneOrganization(org) + formatOneOrganization(response.Payload) return nil }, } @@ -110,11 +113,12 @@ var orgListCmd = &cobra.Command{ return errNeedsInitError } - orgs, err := cli.ListOrganizations() + listOrgsReq := apiClientOrgs.NewListOrgsParams() + response, err := apiCli.Organizations.ListOrgs(listOrgsReq, authToken) if err != nil { return err } - formatOrganizations(orgs) + formatOrganizations(response.Payload) return nil }, } @@ -134,11 +138,13 @@ var orgShowCmd = &cobra.Command{ if len(args) > 1 { return fmt.Errorf("too many arguments") } - org, err := cli.GetOrganization(args[0]) + showOrgReq := apiClientOrgs.NewGetOrgParams() + showOrgReq.OrgID = args[0] + response, err := apiCli.Organizations.GetOrg(showOrgReq, authToken) if err != nil { return err } - formatOneOrganization(org) + formatOneOrganization(response.Payload) return nil }, } @@ -159,7 +165,9 @@ var orgDeleteCmd = &cobra.Command{ if len(args) > 1 { return fmt.Errorf("too many arguments") } - if err := cli.DeleteOrganization(args[0]); err != nil { + deleteOrgReq := apiClientOrgs.NewDeleteOrgParams() + deleteOrgReq.OrgID = args[0] + if err := apiCli.Organizations.DeleteOrg(deleteOrgReq, authToken); err != nil { return err } return nil diff --git a/cmd/garm-cli/cmd/pool.go b/cmd/garm-cli/cmd/pool.go index 8e1e994b..024a58b7 100644 --- a/cmd/garm-cli/cmd/pool.go +++ b/cmd/garm-cli/cmd/pool.go @@ -20,11 +20,18 @@ import ( "os" "strings" + apiClientEnterprises "github.com/cloudbase/garm/client/enterprises" + apiClientOrgs "github.com/cloudbase/garm/client/organizations" + apiClientPools "github.com/cloudbase/garm/client/pools" + apiClientRepos "github.com/cloudbase/garm/client/repositories" + "github.com/cloudbase/garm/params" "github.com/jedib0t/go-pretty/v6/table" "github.com/pkg/errors" "github.com/spf13/cobra" + + commonParams "github.com/cloudbase/garm-provider-common/params" ) var ( @@ -94,13 +101,28 @@ Example: switch len(args) { case 0: if cmd.Flags().Changed("repo") { - pools, err = cli.ListRepoPools(poolRepository) + var response *apiClientRepos.ListRepoPoolsOK + listRepoPoolsReq := apiClientRepos.NewListRepoPoolsParams() + listRepoPoolsReq.RepoID = poolRepository + response, err = apiCli.Repositories.ListRepoPools(listRepoPoolsReq, authToken) + pools = response.Payload } else if cmd.Flags().Changed("org") { - pools, err = cli.ListOrgPools(poolOrganization) + var response *apiClientOrgs.ListOrgPoolsOK + listOrgPoolsReq := apiClientOrgs.NewListOrgPoolsParams() + listOrgPoolsReq.OrgID = poolOrganization + response, err = apiCli.Organizations.ListOrgPools(listOrgPoolsReq, authToken) + pools = response.Payload } else if cmd.Flags().Changed("enterprise") { - pools, err = cli.ListEnterprisePools(poolEnterprise) + var response *apiClientEnterprises.ListEnterprisePoolsOK + listEnterprisePoolsReq := apiClientEnterprises.NewListEnterprisePoolsParams() + listEnterprisePoolsReq.EnterpriseID = poolEnterprise + response, err = apiCli.Enterprises.ListEnterprisePools(listEnterprisePoolsReq, authToken) + pools = response.Payload } else if cmd.Flags().Changed("all") { - pools, err = cli.ListAllPools() + var response *apiClientPools.ListPoolsOK + listPoolsReq := apiClientPools.NewListPoolsParams() + response, err = apiCli.Pools.ListPools(listPoolsReq, authToken) + pools = response.Payload } else { cmd.Help() //nolint os.Exit(0) @@ -136,11 +158,13 @@ var poolShowCmd = &cobra.Command{ return fmt.Errorf("too many arguments") } - pool, err := cli.GetPoolByID(args[0]) + getPoolReq := apiClientPools.NewGetPoolParams() + getPoolReq.PoolID = args[0] + response, err := apiCli.Pools.GetPool(getPoolReq, authToken) if err != nil { return err } - formatOnePool(pool) + formatOnePool(response.Payload) return nil }, } @@ -164,7 +188,9 @@ var poolDeleteCmd = &cobra.Command{ return fmt.Errorf("too many arguments") } - if err := cli.DeletePoolByID(args[0]); err != nil { + deletePoolReq := apiClientPools.NewDeletePoolParams() + deletePoolReq.PoolID = args[0] + if err := apiCli.Pools.DeletePool(deletePoolReq, authToken); err != nil { return err } return nil @@ -192,8 +218,8 @@ var poolAddCmd = &cobra.Command{ MinIdleRunners: poolMinIdleRunners, Image: poolImage, Flavor: poolFlavor, - OSType: params.OSType(poolOSType), - OSArch: params.OSArch(poolOSArch), + OSType: commonParams.OSType(poolOSType), + OSArch: commonParams.OSArch(poolOSArch), Tags: tags, Enabled: poolEnabled, RunnerBootstrapTimeout: poolRunnerBootstrapTimeout, @@ -224,11 +250,26 @@ var poolAddCmd = &cobra.Command{ var err error if cmd.Flags().Changed("repo") { - pool, err = cli.CreateRepoPool(poolRepository, newPoolParams) + var response *apiClientRepos.CreateRepoPoolOK + newRepoPoolReq := apiClientRepos.NewCreateRepoPoolParams() + newRepoPoolReq.RepoID = poolRepository + newRepoPoolReq.Body = newPoolParams + response, err = apiCli.Repositories.CreateRepoPool(newRepoPoolReq, authToken) + pool = response.Payload } else if cmd.Flags().Changed("org") { - pool, err = cli.CreateOrgPool(poolOrganization, newPoolParams) + var response *apiClientOrgs.CreateOrgPoolOK + newOrgPoolReq := apiClientOrgs.NewCreateOrgPoolParams() + newOrgPoolReq.OrgID = poolOrganization + newOrgPoolReq.Body = newPoolParams + response, err = apiCli.Organizations.CreateOrgPool(newOrgPoolReq, authToken) + pool = response.Payload } else if cmd.Flags().Changed("enterprise") { - pool, err = cli.CreateEnterprisePool(poolEnterprise, newPoolParams) + var response *apiClientEnterprises.CreateEnterprisePoolOK + newEnterprisePoolReq := apiClientEnterprises.NewCreateEnterprisePoolParams() + newEnterprisePoolReq.EnterpriseID = poolEnterprise + newEnterprisePoolReq.Body = newPoolParams + response, err = apiCli.Enterprises.CreateEnterprisePool(newEnterprisePoolReq, authToken) + pool = response.Payload } else { cmd.Help() //nolint os.Exit(0) @@ -265,6 +306,7 @@ explicitly remove them using the runner delete command. return fmt.Errorf("too many arguments") } + updatePoolReq := apiClientPools.NewUpdatePoolParams() poolUpdateParams := params.UpdatePoolParams{} if cmd.Flags().Changed("image") { @@ -280,11 +322,11 @@ explicitly remove them using the runner delete command. } if cmd.Flags().Changed("os-type") { - poolUpdateParams.OSType = params.OSType(poolOSType) + poolUpdateParams.OSType = commonParams.OSType(poolOSType) } if cmd.Flags().Changed("os-arch") { - poolUpdateParams.OSArch = params.OSArch(poolOSArch) + poolUpdateParams.OSArch = commonParams.OSArch(poolOSArch) } if cmd.Flags().Changed("max-runners") { @@ -329,12 +371,14 @@ explicitly remove them using the runner delete command. poolUpdateParams.ExtraSpecs = data } - pool, err := cli.UpdatePoolByID(args[0], poolUpdateParams) + updatePoolReq.PoolID = args[0] + updatePoolReq.Body = poolUpdateParams + response, err := apiCli.Pools.UpdatePool(updatePoolReq, authToken) if err != nil { return err } - formatOnePool(pool) + formatOnePool(response.Payload) return nil }, } diff --git a/cmd/garm-cli/cmd/profile.go b/cmd/garm-cli/cmd/profile.go index 29c74323..71843df8 100644 --- a/cmd/garm-cli/cmd/profile.go +++ b/cmd/garm-cli/cmd/profile.go @@ -18,6 +18,7 @@ import ( "fmt" "strings" + apiClientLogin "github.com/cloudbase/garm/client/login" "github.com/cloudbase/garm/cmd/garm-cli/common" "github.com/cloudbase/garm/cmd/garm-cli/config" "github.com/cloudbase/garm/params" @@ -143,12 +144,15 @@ var profileAddCmd = &cobra.Command{ } url := strings.TrimSuffix(loginURL, "/") - loginParams := params.PasswordLoginParams{ + + initApiClient(url, "") + + newLoginParamsReq := apiClientLogin.NewLoginParams() + newLoginParamsReq.Body = params.PasswordLoginParams{ Username: loginUserName, Password: loginPassword, } - - resp, err := cli.Login(url, loginParams) + resp, err := apiCli.Login.Login(newLoginParamsReq, authToken) if err != nil { return err } @@ -156,7 +160,7 @@ var profileAddCmd = &cobra.Command{ cfg.Managers = append(cfg.Managers, config.Manager{ Name: loginProfileName, BaseURL: url, - Token: resp, + Token: resp.Payload.Token, }) cfg.ActiveManager = loginProfileName @@ -190,16 +194,17 @@ installation, by performing a login. return err } - loginParams := params.PasswordLoginParams{ + newLoginParamsReq := apiClientLogin.NewLoginParams() + newLoginParamsReq.Body = params.PasswordLoginParams{ Username: loginUserName, Password: loginPassword, } - resp, err := cli.Login(mgr.BaseURL, loginParams) + resp, err := apiCli.Login.Login(newLoginParamsReq, authToken) if err != nil { return err } - if err := cfg.SetManagerToken(mgr.Name, resp); err != nil { + if err := cfg.SetManagerToken(mgr.Name, resp.Payload.Token); err != nil { return fmt.Errorf("error saving new token: %s", err) } diff --git a/cmd/garm-cli/cmd/provider.go b/cmd/garm-cli/cmd/provider.go index 40840abf..e9635dd0 100644 --- a/cmd/garm-cli/cmd/provider.go +++ b/cmd/garm-cli/cmd/provider.go @@ -17,6 +17,7 @@ package cmd import ( "fmt" + apiClientProviders "github.com/cloudbase/garm/client/providers" "github.com/cloudbase/garm/params" "github.com/jedib0t/go-pretty/v6/table" @@ -49,11 +50,12 @@ func init() { return errNeedsInitError } - providers, err := cli.ListProviders() + listProvidersReq := apiClientProviders.NewListProvidersParams() + response, err := apiCli.Providers.ListProviders(listProvidersReq, authToken) if err != nil { return err } - formatProviders(providers) + formatProviders(response.Payload) return nil }, }) diff --git a/cmd/garm-cli/cmd/repository.go b/cmd/garm-cli/cmd/repository.go index 49b86a0a..8466b318 100644 --- a/cmd/garm-cli/cmd/repository.go +++ b/cmd/garm-cli/cmd/repository.go @@ -17,6 +17,7 @@ package cmd import ( "fmt" + apiClientRepos "github.com/cloudbase/garm/client/repositories" "github.com/cloudbase/garm/params" "github.com/jedib0t/go-pretty/v6/table" @@ -55,17 +56,18 @@ var repoAddCmd = &cobra.Command{ return errNeedsInitError } - newRepoReq := params.CreateRepoParams{ + newRepoReq := apiClientRepos.NewCreateRepoParams() + newRepoReq.Body = params.CreateRepoParams{ Owner: repoOwner, Name: repoName, WebhookSecret: repoWebhookSecret, CredentialsName: repoCreds, } - repo, err := cli.CreateRepository(newRepoReq) + response, err := apiCli.Repositories.CreateRepo(newRepoReq, authToken) if err != nil { return err } - formatOneRepository(repo) + formatOneRepository(response.Payload) return nil }, } @@ -81,11 +83,12 @@ var repoListCmd = &cobra.Command{ return errNeedsInitError } - repos, err := cli.ListRepositories() + listReposReq := apiClientRepos.NewListReposParams() + response, err := apiCli.Repositories.ListRepos(listReposReq, authToken) if err != nil { return err } - formatRepositories(repos) + formatRepositories(response.Payload) return nil }, } @@ -107,16 +110,18 @@ var repoUpdateCmd = &cobra.Command{ if len(args) > 1 { return fmt.Errorf("too many arguments") } - - repoUpdateReq := params.UpdateEntityParams{ + updateReposReq := apiClientRepos.NewUpdateRepoParams() + updateReposReq.Body = params.UpdateEntityParams{ WebhookSecret: repoWebhookSecret, CredentialsName: repoCreds, } - repo, err := cli.UpdateRepo(args[0], repoUpdateReq) + updateReposReq.RepoID = args[0] + + response, err := apiCli.Repositories.UpdateRepo(updateReposReq, authToken) if err != nil { return err } - formatOneRepository(repo) + formatOneRepository(response.Payload) return nil }, } @@ -136,11 +141,13 @@ var repoShowCmd = &cobra.Command{ if len(args) > 1 { return fmt.Errorf("too many arguments") } - repo, err := cli.GetRepository(args[0]) + showRepoReq := apiClientRepos.NewGetRepoParams() + showRepoReq.RepoID = args[0] + response, err := apiCli.Repositories.GetRepo(showRepoReq, authToken) if err != nil { return err } - formatOneRepository(repo) + formatOneRepository(response.Payload) return nil }, } @@ -161,7 +168,9 @@ var repoDeleteCmd = &cobra.Command{ if len(args) > 1 { return fmt.Errorf("too many arguments") } - if err := cli.DeleteRepository(args[0]); err != nil { + deleteRepoReq := apiClientRepos.NewDeleteRepoParams() + deleteRepoReq.RepoID = args[0] + if err := apiCli.Repositories.DeleteRepo(deleteRepoReq, authToken); err != nil { return err } return nil diff --git a/cmd/garm-cli/cmd/root.go b/cmd/garm-cli/cmd/root.go index 716b8038..c491e263 100644 --- a/cmd/garm-cli/cmd/root.go +++ b/cmd/garm-cli/cmd/root.go @@ -16,11 +16,14 @@ package cmd import ( "fmt" + "net/url" "os" - "github.com/cloudbase/garm/cmd/garm-cli/client" + apiClient "github.com/cloudbase/garm/client" "github.com/cloudbase/garm/cmd/garm-cli/config" + "github.com/go-openapi/runtime" + openapiRuntimeClient "github.com/go-openapi/runtime/client" "github.com/spf13/cobra" ) @@ -29,8 +32,8 @@ var Version string var ( cfg *config.Config mgr config.Manager - cli *client.Client - active string + apiCli *apiClient.GarmAPI + authToken runtime.ClientAuthInfoWriter needsInit bool debug bool errNeedsInitError = fmt.Errorf("please log into a garm installation first") @@ -55,6 +58,28 @@ func Execute() { } } +func initApiClient(baseUrl, token string) { + baseUrlParsed, err := url.Parse(baseUrl) + if err != nil { + fmt.Printf("Failed to parse base url %s: %s", baseUrl, err) + os.Exit(1) + } + apiPath, err := url.JoinPath(baseUrlParsed.Path, apiClient.DefaultBasePath) + if err != nil { + fmt.Printf("Failed to join base url path %s with %s: %s", baseUrlParsed.Path, apiClient.DefaultBasePath, err) + os.Exit(1) + } + if debug { + os.Setenv("SWAGGER_DEBUG", "true") + } + transportCfg := apiClient.DefaultTransportConfig(). + WithHost(baseUrlParsed.Host). + WithBasePath(apiPath). + WithSchemes([]string{baseUrlParsed.Scheme}) + apiCli = apiClient.NewHTTPClientWithConfig(nil, transportCfg) + authToken = openapiRuntimeClient.BearerToken(token) +} + func initConfig() { var err error cfg, err = config.LoadConfig() @@ -70,7 +95,6 @@ func initConfig() { if err != nil { mgr = cfg.Managers[0] } - active = mgr.Name } - cli = client.NewClient(active, mgr, debug) + initApiClient(mgr.BaseURL, mgr.Token) } diff --git a/cmd/garm-cli/cmd/runner.go b/cmd/garm-cli/cmd/runner.go index ea17ea26..b4cfbcfe 100644 --- a/cmd/garm-cli/cmd/runner.go +++ b/cmd/garm-cli/cmd/runner.go @@ -20,6 +20,10 @@ import ( "github.com/cloudbase/garm/params" + apiClientEnterprises "github.com/cloudbase/garm/client/enterprises" + apiClientInstances "github.com/cloudbase/garm/client/instances" + apiClientOrgs "github.com/cloudbase/garm/client/organizations" + apiClientRepos "github.com/cloudbase/garm/client/repositories" "github.com/jedib0t/go-pretty/v6/table" "github.com/spf13/cobra" ) @@ -88,16 +92,35 @@ Example: return fmt.Errorf("specifying a pool ID and any of [all org repo enterprise] are mutually exclusive") } - instances, err = cli.ListPoolInstances(args[0]) + var response *apiClientInstances.ListPoolInstancesOK + listPoolInstancesReq := apiClientInstances.NewListPoolInstancesParams() + listPoolInstancesReq.PoolID = args[0] + response, err = apiCli.Instances.ListPoolInstances(listPoolInstancesReq, authToken) + instances = response.Payload case 0: if cmd.Flags().Changed("repo") { - instances, err = cli.ListRepoInstances(runnerRepository) + var response *apiClientRepos.ListRepoInstancesOK + listRepoInstancesReq := apiClientRepos.NewListRepoInstancesParams() + listRepoInstancesReq.RepoID = runnerRepository + response, err = apiCli.Repositories.ListRepoInstances(listRepoInstancesReq, authToken) + instances = response.Payload } else if cmd.Flags().Changed("org") { - instances, err = cli.ListOrgInstances(runnerOrganization) + var response *apiClientOrgs.ListOrgInstancesOK + listOrgInstancesReq := apiClientOrgs.NewListOrgInstancesParams() + listOrgInstancesReq.OrgID = runnerOrganization + response, err = apiCli.Organizations.ListOrgInstances(listOrgInstancesReq, authToken) + instances = response.Payload } else if cmd.Flags().Changed("enterprise") { - instances, err = cli.ListEnterpriseInstances(runnerEnterprise) + var response *apiClientEnterprises.ListEnterpriseInstancesOK + listEnterpriseInstancesReq := apiClientEnterprises.NewListEnterpriseInstancesParams() + listEnterpriseInstancesReq.EnterpriseID = runnerEnterprise + response, err = apiCli.Enterprises.ListEnterpriseInstances(listEnterpriseInstancesReq, authToken) + instances = response.Payload } else if cmd.Flags().Changed("all") { - instances, err = cli.ListAllInstances() + var response *apiClientInstances.ListInstancesOK + listInstancesReq := apiClientInstances.NewListInstancesParams() + response, err = apiCli.Instances.ListInstances(listInstancesReq, authToken) + instances = response.Payload } else { cmd.Help() //nolint os.Exit(0) @@ -133,11 +156,13 @@ var runnerShowCmd = &cobra.Command{ return fmt.Errorf("too many arguments") } - instance, err := cli.GetInstanceByName(args[0]) + showInstanceReq := apiClientInstances.NewGetInstanceParams() + showInstanceReq.InstanceName = args[0] + response, err := apiCli.Instances.GetInstance(showInstanceReq, authToken) if err != nil { return err } - formatSingleInstance(instance) + formatSingleInstance(response.Payload) return nil }, } @@ -170,7 +195,9 @@ to either cancel the workflow or wait for it to finish. return fmt.Errorf("use --force-remove-runner=true to remove a runner") } - if err := cli.DeleteRunner(args[0]); err != nil { + deleteInstanceReq := apiClientInstances.NewDeleteInstanceParams() + deleteInstanceReq.InstanceName = args[0] + if err := apiCli.Instances.DeleteInstance(deleteInstanceReq, authToken); err != nil { return err } return nil diff --git a/cmd/garm-cli/config/config.go b/cmd/garm-cli/config/config.go index 133b38da..6f6b197c 100644 --- a/cmd/garm-cli/config/config.go +++ b/cmd/garm-cli/config/config.go @@ -23,7 +23,7 @@ import ( "github.com/BurntSushi/toml" "github.com/pkg/errors" - runnerErrors "github.com/cloudbase/garm/errors" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" ) const ( diff --git a/cmd/garm/main.go b/cmd/garm/main.go index d6634dd0..04a45f0b 100644 --- a/cmd/garm/main.go +++ b/cmd/garm/main.go @@ -27,6 +27,7 @@ import ( "syscall" "time" + "github.com/cloudbase/garm-provider-common/util" "github.com/cloudbase/garm/apiserver/controllers" "github.com/cloudbase/garm/apiserver/routers" "github.com/cloudbase/garm/auth" @@ -35,7 +36,6 @@ import ( "github.com/cloudbase/garm/database/common" "github.com/cloudbase/garm/metrics" "github.com/cloudbase/garm/runner" - "github.com/cloudbase/garm/util" "github.com/cloudbase/garm/util/appdefaults" "github.com/cloudbase/garm/websocket" lumberjack "gopkg.in/natefinch/lumberjack.v2" @@ -52,6 +52,11 @@ var ( var Version string +var signals = []os.Signal{ + os.Interrupt, + syscall.SIGTERM, +} + func maybeInitController(db common.Store) error { if _, err := db.ControllerInfo(); err == nil { return nil @@ -79,7 +84,7 @@ func main() { log.Fatalf("Fetching config: %+v", err) } - logWriter, err := util.GetLoggingWriter(cfg) + logWriter, err := util.GetLoggingWriter(cfg.Default.LogFile) if err != nil { log.Fatalf("fetching log writer: %+v", err) } diff --git a/cmd/garm/signal_nix.go b/cmd/garm/signal_nix.go deleted file mode 100644 index 152b2d96..00000000 --- a/cmd/garm/signal_nix.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build !windows -// +build !windows - -package main - -import ( - "os" - "syscall" -) - -var signals = []os.Signal{ - os.Interrupt, - syscall.SIGTERM, -} diff --git a/cmd/garm/signal_windows.go b/cmd/garm/signal_windows.go deleted file mode 100644 index b424d6dd..00000000 --- a/cmd/garm/signal_windows.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build windows && !linux -// +build windows,!linux - -package main - -import "os" - -var signals = []os.Signal{ - os.Interrupt, -} diff --git a/config/config.go b/config/config.go index a0eca1e3..a65c4668 100644 --- a/config/config.go +++ b/config/config.go @@ -47,9 +47,6 @@ func NewConfig(cfgFile string) (*Config, error) { if _, err := toml.DecodeFile(cfgFile, &config); err != nil { return nil, errors.Wrap(err, "decoding toml") } - if config.Default.ConfigDir == "" { - config.Default.ConfigDir = appdefaults.DefaultConfigDir - } if err := config.Validate(); err != nil { return nil, errors.Wrap(err, "validating config") } @@ -108,10 +105,6 @@ func (c *Config) Validate() error { } type Default struct { - // ConfigDir is the folder where the runner may save any aditional files - // or configurations it may need. Things like auto-generated SSH keys that - // may be used to access the runner instances. - ConfigDir string `toml:"config_dir,omitempty" json:"config-dir,omitempty"` // CallbackURL is the URL where the instances can send back status reports. CallbackURL string `toml:"callback_url" json:"callback-url"` // MetadataURL is the URL where instances can fetch information they may need @@ -139,14 +132,6 @@ func (d *Default) Validate() error { return errors.Wrap(err, "validating metadata_url") } - if d.ConfigDir == "" { - return fmt.Errorf("config_dir cannot be empty") - } - - if _, err := os.Stat(d.ConfigDir); err != nil { - return errors.Wrap(err, "accessing config dir") - } - return nil } diff --git a/config/config_test.go b/config/config_test.go index 210b0fce..e7f8489f 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -32,7 +32,6 @@ var ( func getDefaultSectionConfig(configDir string) Default { return Default{ - ConfigDir: configDir, CallbackURL: "https://garm.example.com/", MetadataURL: "https://garm.example.com/api/v1/metadata", LogFile: filepath.Join(configDir, "garm.log"), @@ -152,7 +151,6 @@ func TestDefaultSectionConfig(t *testing.T) { cfg: Default{ CallbackURL: "", MetadataURL: cfg.MetadataURL, - ConfigDir: cfg.ConfigDir, }, errString: "missing callback_url", }, @@ -161,28 +159,9 @@ func TestDefaultSectionConfig(t *testing.T) { cfg: Default{ CallbackURL: cfg.CallbackURL, MetadataURL: "", - ConfigDir: cfg.ConfigDir, }, errString: "missing metadata-url", }, - { - name: "ConfigDir cannot be empty", - cfg: Default{ - CallbackURL: cfg.CallbackURL, - MetadataURL: cfg.MetadataURL, - ConfigDir: "", - }, - errString: "config_dir cannot be empty", - }, - { - name: "config_dir must exist and be accessible", - cfg: Default{ - CallbackURL: cfg.CallbackURL, - MetadataURL: cfg.MetadataURL, - ConfigDir: "/i/do/not/exist", - }, - errString: "accessing config dir: stat /i/do/not/exist:.*", - }, } for _, tc := range tests { @@ -560,7 +539,6 @@ func TestNewConfig(t *testing.T) { require.Nil(t, err) require.NotNil(t, cfg) require.Equal(t, "https://garm.example.com/", cfg.Default.CallbackURL) - require.Equal(t, "./testdata", cfg.Default.ConfigDir) require.Equal(t, "0.0.0.0", cfg.APIServer.Bind) require.Equal(t, 9998, cfg.APIServer.Port) require.Equal(t, false, cfg.APIServer.UseTLS) @@ -574,31 +552,6 @@ func TestNewConfig(t *testing.T) { require.Equal(t, timeToLive("48h"), cfg.JWTAuth.TimeToLive) } -func TestNewConfigEmptyConfigDir(t *testing.T) { - dirPath, err := os.MkdirTemp("", "garm-config-test") - if err != nil { - t.Fatalf("failed to create temporary directory: %s", err) - } - defer os.RemoveAll(dirPath) - appdefaults.DefaultConfigDir = dirPath - - cfg, err := NewConfig("testdata/test-empty-config-dir.toml") - require.Nil(t, err) - require.NotNil(t, cfg) - require.Equal(t, cfg.Default.ConfigDir, dirPath) - require.Equal(t, "https://garm.example.com/", cfg.Default.CallbackURL) - require.Equal(t, "0.0.0.0", cfg.APIServer.Bind) - require.Equal(t, 9998, cfg.APIServer.Port) - require.Equal(t, false, cfg.APIServer.UseTLS) - require.Equal(t, DBBackendType("mysql"), cfg.Database.DbBackend) - require.Equal(t, "test", cfg.Database.MySQL.Username) - require.Equal(t, "test", cfg.Database.MySQL.Password) - require.Equal(t, "127.0.0.1", cfg.Database.MySQL.Hostname) - require.Equal(t, "garm", cfg.Database.MySQL.DatabaseName) - require.Equal(t, "bocyasicgatEtenOubwonIbsudNutDom", cfg.JWTAuth.Secret) - require.Equal(t, timeToLive("48h"), cfg.JWTAuth.TimeToLive) -} - func TestNewConfigInvalidTomlPath(t *testing.T) { cfg, err := NewConfig("this is not a file path") require.Nil(t, cfg) diff --git a/config/external.go b/config/external.go index c6195dcb..5bd9e273 100644 --- a/config/external.go +++ b/config/external.go @@ -19,7 +19,7 @@ import ( "os" "path/filepath" - "github.com/cloudbase/garm/util/exec" + "github.com/cloudbase/garm-provider-common/util/exec" "github.com/pkg/errors" ) diff --git a/database/sql/controller.go b/database/sql/controller.go index 3b7a9166..7c2baf65 100644 --- a/database/sql/controller.go +++ b/database/sql/controller.go @@ -15,7 +15,7 @@ package sql import ( - runnerErrors "github.com/cloudbase/garm/errors" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/params" "github.com/google/uuid" diff --git a/database/sql/controller_test.go b/database/sql/controller_test.go index f7992465..7f82160c 100644 --- a/database/sql/controller_test.go +++ b/database/sql/controller_test.go @@ -19,8 +19,8 @@ import ( "fmt" "testing" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" dbCommon "github.com/cloudbase/garm/database/common" - runnerErrors "github.com/cloudbase/garm/errors" garmTesting "github.com/cloudbase/garm/internal/testing" "github.com/stretchr/testify/suite" diff --git a/database/sql/enterprise.go b/database/sql/enterprise.go index 005e3bc6..0a1ea81b 100644 --- a/database/sql/enterprise.go +++ b/database/sql/enterprise.go @@ -3,9 +3,9 @@ package sql import ( "context" - runnerErrors "github.com/cloudbase/garm/errors" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" + "github.com/cloudbase/garm-provider-common/util" "github.com/cloudbase/garm/params" - "github.com/cloudbase/garm/util" "github.com/google/uuid" "github.com/pkg/errors" diff --git a/database/sql/enterprise_test.go b/database/sql/enterprise_test.go index cc927f6c..91e45898 100644 --- a/database/sql/enterprise_test.go +++ b/database/sql/enterprise_test.go @@ -24,8 +24,8 @@ import ( "github.com/cloudbase/garm/params" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" dbCommon "github.com/cloudbase/garm/database/common" - runnerErrors "github.com/cloudbase/garm/errors" garmTesting "github.com/cloudbase/garm/internal/testing" "github.com/stretchr/testify/suite" diff --git a/database/sql/instances.go b/database/sql/instances.go index bc16be90..12c833af 100644 --- a/database/sql/instances.go +++ b/database/sql/instances.go @@ -18,7 +18,7 @@ import ( "context" "encoding/json" - runnerErrors "github.com/cloudbase/garm/errors" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/params" "github.com/google/uuid" diff --git a/database/sql/instances_test.go b/database/sql/instances_test.go index 5f6fc984..d47b265e 100644 --- a/database/sql/instances_test.go +++ b/database/sql/instances_test.go @@ -22,10 +22,11 @@ import ( "sort" "testing" + commonParams "github.com/cloudbase/garm-provider-common/params" + dbCommon "github.com/cloudbase/garm/database/common" garmTesting "github.com/cloudbase/garm/internal/testing" "github.com/cloudbase/garm/params" - "github.com/cloudbase/garm/runner/providers/common" "gopkg.in/DATA-DOG/go-sqlmock.v1" @@ -109,8 +110,8 @@ func (s *InstancesTestSuite) SetupTest() { OSType: "linux", OSArch: "amd64", CallbackURL: "https://garm.example.com/", - Status: common.InstanceRunning, - RunnerStatus: common.RunnerIdle, + Status: commonParams.InstanceRunning, + RunnerStatus: params.RunnerIdle, }, ) if err != nil { @@ -156,18 +157,18 @@ func (s *InstancesTestSuite) SetupTest() { ProviderID: "update-provider-test", OSName: "ubuntu", OSVersion: "focal", - Status: common.InstancePendingDelete, - RunnerStatus: common.RunnerActive, + Status: commonParams.InstancePendingDelete, + RunnerStatus: params.RunnerActive, AgentID: 4, CreateAttempt: 3, - Addresses: []params.Address{ + Addresses: []commonParams.Address{ { Address: "12.10.12.10", - Type: params.PublicAddress, + Type: commonParams.PublicAddress, }, { Address: "10.1.1.2", - Type: params.PrivateAddress, + Type: commonParams.PrivateAddress, }, }, }, diff --git a/database/sql/jobs.go b/database/sql/jobs.go index ffe14378..091dfd7c 100644 --- a/database/sql/jobs.go +++ b/database/sql/jobs.go @@ -4,8 +4,8 @@ import ( "context" "encoding/json" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/database/common" - runnerErrors "github.com/cloudbase/garm/errors" "github.com/cloudbase/garm/params" "github.com/google/uuid" "github.com/pkg/errors" diff --git a/database/sql/models.go b/database/sql/models.go index 3404be69..86a343cc 100644 --- a/database/sql/models.go +++ b/database/sql/models.go @@ -17,8 +17,8 @@ package sql import ( "time" + commonParams "github.com/cloudbase/garm-provider-common/params" "github.com/cloudbase/garm/params" - "github.com/cloudbase/garm/runner/providers/common" "github.com/google/uuid" "github.com/pkg/errors" @@ -63,8 +63,8 @@ type Pool struct { RunnerBootstrapTimeout uint Image string `gorm:"index:idx_pool_type"` Flavor string `gorm:"index:idx_pool_type"` - OSType params.OSType - OSArch params.OSArch + OSType commonParams.OSType + OSArch commonParams.OSArch Tags []*Tag `gorm:"many2many:pool_tags;constraint:OnDelete:CASCADE,OnUpdate:CASCADE;"` Enabled bool // ExtraSpecs is an opaque json that gets sent to the provider @@ -143,13 +143,13 @@ type Instance struct { ProviderID *string `gorm:"uniqueIndex"` Name string `gorm:"uniqueIndex"` AgentID int64 - OSType params.OSType - OSArch params.OSArch + OSType commonParams.OSType + OSArch commonParams.OSArch OSName string OSVersion string Addresses []Address `gorm:"foreignKey:InstanceID;constraint:OnDelete:CASCADE,OnUpdate:CASCADE;"` - Status common.InstanceStatus - RunnerStatus common.RunnerStatus + Status commonParams.InstanceStatus + RunnerStatus params.RunnerStatus CallbackURL string MetadataURL string ProviderFault []byte `gorm:"type:longblob"` diff --git a/database/sql/organizations.go b/database/sql/organizations.go index 4a7d27d7..c0a48d4d 100644 --- a/database/sql/organizations.go +++ b/database/sql/organizations.go @@ -18,9 +18,9 @@ import ( "context" "fmt" - runnerErrors "github.com/cloudbase/garm/errors" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" + "github.com/cloudbase/garm-provider-common/util" "github.com/cloudbase/garm/params" - "github.com/cloudbase/garm/util" "github.com/google/uuid" "github.com/pkg/errors" diff --git a/database/sql/organizations_test.go b/database/sql/organizations_test.go index 7cc9c59f..b664fc8b 100644 --- a/database/sql/organizations_test.go +++ b/database/sql/organizations_test.go @@ -22,8 +22,8 @@ import ( "sort" "testing" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" dbCommon "github.com/cloudbase/garm/database/common" - runnerErrors "github.com/cloudbase/garm/errors" garmTesting "github.com/cloudbase/garm/internal/testing" "github.com/cloudbase/garm/params" diff --git a/database/sql/pools.go b/database/sql/pools.go index 1f68fd4f..7990e9d3 100644 --- a/database/sql/pools.go +++ b/database/sql/pools.go @@ -18,7 +18,7 @@ import ( "context" "fmt" - runnerErrors "github.com/cloudbase/garm/errors" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/params" "github.com/google/uuid" diff --git a/database/sql/repositories.go b/database/sql/repositories.go index f6fd045c..007a2f6e 100644 --- a/database/sql/repositories.go +++ b/database/sql/repositories.go @@ -18,9 +18,9 @@ import ( "context" "fmt" - runnerErrors "github.com/cloudbase/garm/errors" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" + "github.com/cloudbase/garm-provider-common/util" "github.com/cloudbase/garm/params" - "github.com/cloudbase/garm/util" "github.com/google/uuid" "github.com/pkg/errors" diff --git a/database/sql/users.go b/database/sql/users.go index 5e40c5cb..78922b80 100644 --- a/database/sql/users.go +++ b/database/sql/users.go @@ -18,9 +18,9 @@ import ( "context" "fmt" - runnerErrors "github.com/cloudbase/garm/errors" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" + "github.com/cloudbase/garm-provider-common/util" "github.com/cloudbase/garm/params" - "github.com/cloudbase/garm/util" "github.com/pkg/errors" "gorm.io/gorm" diff --git a/database/sql/util.go b/database/sql/util.go index 84bffc5c..fa6706d2 100644 --- a/database/sql/util.go +++ b/database/sql/util.go @@ -18,12 +18,14 @@ import ( "encoding/json" "fmt" + "github.com/cloudbase/garm-provider-common/util" "github.com/cloudbase/garm/params" - "github.com/cloudbase/garm/util" "github.com/pkg/errors" "gorm.io/datatypes" "gorm.io/gorm" + + commonParams "github.com/cloudbase/garm-provider-common/params" ) func (s *sqlDatabase) sqlToParamsInstance(instance Instance) params.Instance { @@ -75,10 +77,10 @@ func (s *sqlDatabase) sqlToParamsInstance(instance Instance) params.Instance { return ret } -func (s *sqlDatabase) sqlAddressToParamsAddress(addr Address) params.Address { - return params.Address{ +func (s *sqlDatabase) sqlAddressToParamsAddress(addr Address) commonParams.Address { + return commonParams.Address{ Address: addr.Address, - Type: params.AddressType(addr.Type), + Type: commonParams.AddressType(addr.Type), } } diff --git a/doc/building_from_source.md b/doc/building_from_source.md new file mode 100644 index 00000000..9058820e --- /dev/null +++ b/doc/building_from_source.md @@ -0,0 +1,25 @@ +# Building GARM from source + +The procedure is simple. You will need to gave [go](https://golang.org/) installed as well as `make`. + +First, clone the repository: + +```bash +git clone https://github.com/cloudbase/garm +``` + +Then build garm: + +```bash +make +``` + +You should now have both `garm` and `garm-cli` available in the `./bin` folder. + +If you have docker/podman installed, you can also build a static binary against `musl`: + +```bash +make build-static +``` + +This command will also build for both AMD64 and ARM64. Resulting binaries will be in the `./bin` folder. \ No newline at end of file diff --git a/doc/config_api_server.md b/doc/config_api_server.md new file mode 100644 index 00000000..33f0f4ea --- /dev/null +++ b/doc/config_api_server.md @@ -0,0 +1,34 @@ +# The API server config section + +This section allows you to configure the GARM API server. The API server is responsible for serving all the API endpoints used by the `garm-cli`, the runners that phone home their status and by GitHub when it sends us webhooks. + +The config options are fairly straight forward. + +```toml +[apiserver] + # Bind the API to this IP + bind = "0.0.0.0" + # Bind the API to this port + port = 9997 + # Whether or not to set up TLS for the API endpoint. If this is set to true, + # you must have a valid apiserver.tls section. + use_tls = false + # Set a list of allowed origins + # By default, if this option is ommited or empty, we will check + # only that the origin is the same as the originating server. + # A literal of "*" will allow any origin + cors_origins = ["*"] + [apiserver.tls] + # Path on disk to a x509 certificate bundle. + # NOTE: if your certificate is signed by an intermediary CA, this file + # must contain the entire certificate bundle needed for clients to validate + # the certificate. This usually means concatenating the certificate and the + # CA bundle you received. + certificate = "" + # The path on disk to the corresponding private key for the certificate. + key = "" +``` + +The GARM API server has the option to enable TLS, but I suggest you use a reverse proxy and enable TLS termination in that reverse proxy. There is an `nginx` sample in this repository with TLS termination enabled. + +You can of course enable TLS in both garm and the reverse proxy. The choice is yours. \ No newline at end of file diff --git a/doc/config_default.md b/doc/config_default.md new file mode 100644 index 00000000..ea95132e --- /dev/null +++ b/doc/config_default.md @@ -0,0 +1,169 @@ +# The default config section + +The `default` config section holds configuration options that don't need a category of their own, but are essential to the operation of the service. In this section we will detail each of the options available in the `default` section. + +```toml +[default] +# This URL is used by instances to send back status messages as they install +# the github actions runner. Status messages can be seen by querying the +# runner status in garm. +# Note: If you're using a reverse proxy in front of your garm installation, +# this URL needs to point to the address of the reverse proxy. Using TLS is +# highly encouraged. +callback_url = "https://garm.example.com/api/v1/callbacks/status" + +# This URL is used by instances to retrieve information they need to set themselves +# up. Access to this URL is granted using the same JWT token used to send back +# status updates. Once the instance transitions to "installed" or "failed" state, +# access to both the status and metadata endpoints is disabled. +# Note: If you're using a reverse proxy in front of your garm installation, +# this URL needs to point to the address of the reverse proxy. Using TLS is +# highly encouraged. +metadata_url = "https://garm.example.com/api/v1/metadata" + +# Uncomment this line if you'd like to log to a file instead of standard output. +# log_file = "/tmp/runner-manager.log" + +# Enable streaming logs via web sockets. Use garm-cli debug-log. +enable_log_streamer = false + +# Enable the golang debug server. See the documentation in the "doc" folder for more information. +debug_server = false +``` + +## The callback_url option + +Your runners will call back home with status updates as they install. Once they are set up, they will also send the GitHub agent ID they were allocated. You will need to configure the ```callback_url``` option in the ```garm``` server config. This URL needs to point to the following API endpoint: + + ```txt + POST /api/v1/callbacks/status + ``` + +Example of a runner sending status updates: + + ```bash + garm-cli runner show garm-DvxiVAlfHeE7 + +-----------------+------------------------------------------------------------------------------------+ + | FIELD | VALUE | + +-----------------+------------------------------------------------------------------------------------+ + | ID | 16b96ba2-d406-45b8-ab66-b70be6237b4e | + | Provider ID | garm-DvxiVAlfHeE7 | + | Name | garm-DvxiVAlfHeE7 | + | OS Type | linux | + | OS Architecture | amd64 | + | OS Name | ubuntu | + | OS Version | jammy | + | Status | running | + | Runner Status | idle | + | Pool ID | 8ec34c1f-b053-4a5d-80d6-40afdfb389f9 | + | Addresses | 10.198.117.120 | + | Status Updates | 2023-07-08T06:26:46: runner registration token was retrieved | + | | 2023-07-08T06:26:46: using cached runner found in /opt/cache/actions-runner/latest | + | | 2023-07-08T06:26:50: configuring runner | + | | 2023-07-08T06:26:56: runner successfully configured after 1 attempt(s) | + | | 2023-07-08T06:26:56: installing runner service | + | | 2023-07-08T06:26:56: starting service | + | | 2023-07-08T06:26:57: runner successfully installed | + +-----------------+------------------------------------------------------------------------------------+ + + ``` + +This URL must be set and must be accessible by the instance. If you wish to restrict access to it, a reverse proxy can be configured to accept requests only from networks in which the runners ```garm``` manages will be spun up. This URL doesn't need to be globally accessible, it just needs to be accessible by the instances. + +For example, in a scenario where you expose the API endpoint directly, this setting could look like the following: + + ```toml + callback_url = "https://garm.example.com/api/v1/callbacks/status" + ``` + +Authentication is done using a short-lived JWT token, that gets generated for a particular instance that we are spinning up. That JWT token grants access to the instance to only update it's own status and to fetch metadata for itself. No other API endpoints will work with that JWT token. The validity of the token is equal to the pool bootstrap timeout value (default 20 minutes) plus the garm polling interval (5 minutes). + +There is a sample ```nginx``` config [in the testdata folder](/testdata/nginx-server.conf). Feel free to customize it whichever way you see fit. + +## The metadata_url option + +The metadata URL is the base URL for any information an instance may need to fetch in order to finish setting itself up. As this URL may be placed behind a reverse proxy, you'll need to configure it in the ```garm``` config file. Ultimately this URL will need to point to the following ```garm``` API endpoint: + + ```bash + GET /api/v1/metadata + ``` + +This URL needs to be accessible only by the instances ```garm``` sets up. This URL will not be used by anyone else. To configure it in ```garm``` add the following line in the ```[default]``` section of your ```garm``` config: + + ```toml + metadata_url = "https://garm.example.com/api/v1/metadata" + ``` + +## The debug_server option + +GARM can optionally enable the golang profiling server. This is useful if you suspect garm may be bottlenecking in any way. To enable the profiling server, add the following section to the garm config: + +```toml +[default] + +debug_server = true +``` + +And restart garm. You can then use the following command to start profiling: + +```bash +go tool pprof http://127.0.0.1:9997/debug/pprof/profile?seconds=120 +``` + +Important note on profiling when behind a reverse proxy. The above command will hang for a fairly long time. Most reverse proxies will timeout after about 60 seconds. To avoid this, you should only profile on localhost by connecting directly to garm. + +It's also advisable to exclude the debug server URLs from your reverse proxy and only make them available locally. + +Now that the debug server is enabled, here is a blog post on how to profile golang applications: https://blog.golang.org/profiling-go-programs + + +## The log_file option + +By default, GARM logs everything to standard output. + +You can optionally log to file by adding the following to your config file: + +```toml +[default] +# Use this if you'd like to log to a file instead of standard output. +log_file = "/tmp/runner-manager.log" +``` + +### Rotating log files + +GARM automatically rotates the log if it reaches 500 MB in size or 28 days, whichever comes first. + +However, if you want to manually rotate the log file, you can send a `SIGHUP` signal to the GARM process. + +You can add the following to your systemd unit file to enable `reload`: + +```ini +[Service] +ExecReload=/bin/kill -HUP $MAINPID +``` + +Then you can simply: + +```bash +systemctl reload garm +``` + +## The enable_log_streamer option + +This option allows you to stream garm logs directly to your terminal. Set this option to true, then you can use the following command to stream logs: + +```bash +garm-cli debug-log +``` + +An important note on enabling this option when behind a reverse proxy. The log streamer uses websockets to stream logs to you. You will need to configure your reverse proxy to allow websocket connections. If you're using nginx, you will need to add the following to your nginx `server` config: + +```nginx +location /api/v1/ws { + proxy_pass http://garm_backend; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "Upgrade"; + proxy_set_header Host $host; +} +``` \ No newline at end of file diff --git a/doc/config_jwt_auth.md b/doc/config_jwt_auth.md new file mode 100644 index 00000000..7f07d311 --- /dev/null +++ b/doc/config_jwt_auth.md @@ -0,0 +1,18 @@ +# The JWT authentication config section + +This section configures the JWT authentication used by the API server. GARM is currently a single user system and that user has the right to do anything and everything GARM is capable of. As a result, the JWT auth we have does not include a refresh token. The token is valid for the duration of the time to live (TTL) set in the config file. Once the token expires, you will need to log in again. + +It is recommended that the secret be a long, randomly generated string. Changing the secret at any time will invalidate all existing tokens. + +```toml +[jwt_auth] +# A JWT token secret used to sign tokens. Obviously, this needs to be changed :). +secret = ")9gk_4A6KrXz9D2u`0@MPea*sd6W`%@5MAWpWWJ3P3EqW~qB!!(Vd$FhNc*eU4vG" + +# Time to live for tokens. Both the instances and you will use JWT tokens to +# authenticate against the API. However, this TTL is applied only to tokens you +# get when logging into the API. The tokens issued to the instances we manage, +# have a TTL based on the runner bootstrap timeout set on each pool. The minimum +# TTL for this token is 24h. +time_to_live = "8760h" +``` \ No newline at end of file diff --git a/doc/config_metrics.md b/doc/config_metrics.md new file mode 100644 index 00000000..caa50b1b --- /dev/null +++ b/doc/config_metrics.md @@ -0,0 +1,55 @@ +# The metrics section + +This is one of the features in GARM that I really love having. For one thing, it's community contributed and for another, it really adds value to the project. It allows us to create some pretty nice visualizations of what is happening with GARM. + +At the moment there are only three meaningful metrics being collected, besides the default ones that the prometheus golang package enables by default. These are: + +* `garm_health` - This is a gauge that is set to 1 if GARM is healthy and 0 if it is not. This is useful for alerting. +* `garm_runner_status` - This is a gauge value that gives us details about the runners garm spawns +* `garm_webhooks_received` - This is a counter that increments every time GARM receives a webhook from GitHub. + +More metrics will be added in the future. + +## Enabling metrics + +Metrics are disabled by default. To enable them, add the following to your config file: + +```toml +[metrics] +# Toggle metrics. If set to false, the API endpoint for metrics collection will +# be disabled. +enable = true +# Toggle to disable authentication (not recommended) on the metrics endpoint. +# If you do disable authentication, I encourage you to put a reverse proxy in front +# of garm and limit which systems can access that particular endpoint. Ideally, you +# would enable some kind of authentication using the reverse proxy, if the built-in auth +# is not sufficient for your needs. +disable_auth = false +``` + +You can choose to disable authentication if you wish, however it's not terribly difficult to set up, so I generally advise against disabling it. + +## Configuring prometheus + +The following section assumes that your garm instance is running at `garm.example.com` and has TLS enabled. + +First, generate a new JWT token valid only for the metrics endpoint: + +```bash +garm-cli metrics-token create +``` + +Note: The token validity is equal to the TTL you set in the [JWT config section](/doc/config_jwt_auth.md). + +Copy the resulting token, and add it to your prometheus config file. The following is an example of how to add garm as a target in your prometheus config file: + +```yaml +scrape_configs: + - job_name: "garm" + # Connect over https. If you don't have TLS enabled, change this to http. + scheme: https + static_configs: + - targets: ["garm.example.com"] + authorization: + credentials: "superSecretTokenYouGeneratedEarlier" +``` \ No newline at end of file diff --git a/doc/database.md b/doc/database.md index 59204640..c3e1edc6 100644 --- a/doc/database.md +++ b/doc/database.md @@ -1,37 +1,20 @@ # Database configuration -Garm currently supports two database backends: +GARM currently supports SQLite3. Support for other stores will be added in the future. -* SQLite3 -* MySQL - -You can choose either one of these. For most cases, ```SQLite3``` should do, but feel free to go with MySQL if you wish. - - ```toml - [database] - # Turn on/off debugging for database queries. - debug = false - # Database backend to use. Currently supported backends are: - # * sqlite3 - # * mysql - backend = "sqlite3" - # the passphrase option is a temporary measure by which we encrypt the webhook - # secret that gets saved to the database, using AES256. In the future, secrets - # will be saved to something like Barbican or Vault, eliminating the need for - # this. - passphrase = "n<$n&P#L*TWqOh95_bN5J1r4mhxY7R84HZ%pvM#1vxJ<7~q%YVsCwU@Z60;7~Djo" - [database.mysql] - # If MySQL is used, these are the credentials and connection information used - # to connect to the server instance. - # database username - username = "" - # Database password - password = "" - # hostname to connect to - hostname = "" - # database name - database = "" - [database.sqlite3] - # Path on disk to the sqlite3 database file. - db_file = "/home/runner/file.db" - ``` +```toml +[database] + # Turn on/off debugging for database queries. + debug = false + # Database backend to use. Currently supported backends are: + # * sqlite3 + backend = "sqlite3" + # the passphrase option is a temporary measure by which we encrypt the webhook + # secret that gets saved to the database, using AES256. In the future, secrets + # will be saved to something like Barbican or Vault, eliminating the need for + # this. + passphrase = "n<$n&P#L*TWqOh95_bN5J1r4mhxY7R84HZ%pvM#1vxJ<7~q%YVsCwU@Z60;7~Djo" + [database.sqlite3] + # Path on disk to the sqlite3 database file. + db_file = "/home/runner/garm.db" +``` diff --git a/doc/extra_specs.md b/doc/extra_specs.md new file mode 100644 index 00000000..8e55d11e --- /dev/null +++ b/doc/extra_specs.md @@ -0,0 +1,8 @@ +# ExtraSpecs + +ExtraSpecs is an opaque raw json that gets sent to the provider as part of the bootstrap params for instances. It can contain any kind of data needed by providers. The contents of this field means nothing to garm itself. We don't act on the information in this field at all. We only validate that it's a proper json. + +However, during the installation phase of the runners, GARM providers can leverage the information set in this field to augment the process in many ways. This can be used for anything rangin from overriding provider config values, to supplying a different runner install template, to passing in information that is relevant only to specific providers. + +For example, the [external OpenStack provider](https://github.com/cloudbase/garm-provider-openstack) uses this to [override](https://github.com/cloudbase/garm-provider-openstack#tweaking-the-provider) things like `security groups`, `storage backends`, `network ids`, etc. + diff --git a/doc/images/input_url.png b/doc/images/input_url.png new file mode 100644 index 00000000..8cc9ce9f Binary files /dev/null and b/doc/images/input_url.png differ diff --git a/doc/images/jobs.png b/doc/images/jobs.png new file mode 100644 index 00000000..8e808259 Binary files /dev/null and b/doc/images/jobs.png differ diff --git a/doc/images/select_events.png b/doc/images/select_events.png new file mode 100644 index 00000000..0ec5c7e0 Binary files /dev/null and b/doc/images/select_events.png differ diff --git a/doc/images/tls_config.png b/doc/images/tls_config.png new file mode 100644 index 00000000..b06fb18a Binary files /dev/null and b/doc/images/tls_config.png differ diff --git a/doc/images/webhooks.png b/doc/images/webhooks.png new file mode 100644 index 00000000..91210fae Binary files /dev/null and b/doc/images/webhooks.png differ diff --git a/doc/logging.md b/doc/logging.md deleted file mode 100644 index 02eb34c5..00000000 --- a/doc/logging.md +++ /dev/null @@ -1,17 +0,0 @@ -# Logging - -By default, GARM is logging only on standard output. - -If you would like GARM to use a logging file instead, you can use the `log_file` configuration option: - -```toml -[default] -# Use this if you'd like to log to a file instead of standard output. -log_file = "/tmp/runner-manager.log" -``` - -## Rotating log files - -If GARM uses a log file, by default it will rotate it when it reaches 500MB or 28 days, whichever comes first. - -However, if you want to manually rotate the log file, you can send a `SIGHUP` signal to the GARM process. diff --git a/doc/performance_considerations.md b/doc/performance_considerations.md index 568171ef..923586b8 100644 --- a/doc/performance_considerations.md +++ b/doc/performance_considerations.md @@ -2,7 +2,7 @@ Performance is often important when running GitHub action runners with garm. This document shows some ways to improve the creation time of a GitHub action runner. -## garm specific performance considerations +## GARM specific performance considerations ### Bundle the GitHub action runner diff --git a/doc/providers.md b/doc/providers.md index d1042130..7b7d686b 100644 --- a/doc/providers.md +++ b/doc/providers.md @@ -1,35 +1,38 @@ # Provider configuration -Garm was designed to be extensible. The database layer as well as the providers are defined as interfaces. Currently there are two providers: +GARM was designed to be extensible. Providers can be written either as built-in plugins or as external executables. The built-in plugins are written in Go, and they are compiled into the ```GARM``` binary. External providers are executables that implement the needed interface to create/delete/list compute systems that are used by ```GARM``` to create runners. -* [LXD](https://linuxcontainers.org/lxd/introduction/) -* External +GARM currently ships with one built-in provider for [LXD](https://linuxcontainers.org/lxd/introduction/) and the external provider interface which allows you to write your own provider in any language you want. -LXD is the simplest cloud-like system you can easily set up on any GNU/Linux machine, which enables you to create both containers and Virtual Machines. The ```external``` provider is a special type of provider, which delegates functionality to external executables. +- [LXD provider](#lxd-provider) + - [LXD remotes](#lxd-remotes) + - [LXD Security considerations](#lxd-security-considerations) +- [External provider](#external-provider) + - [Available external providers](#available-external-providers) -## The LXD provider +## LXD provider -Garm leverages the virtual machines feature of LXD to create the runners. Here is a sample config section for an LXD provider: +GARM leverages LXD to create the runners. Here is a sample config section for an LXD provider: ```toml # Currently, providers are defined statically in the config. This is due to the fact # that we have not yet added support for storing secrets in something like Barbican # or Vault. This will change in the future. However, for now, it's important to remember # that once you create a pool using one of the providers defined here, the name of that -# provider must not be changes, or the pool will no longer work. Make sure you remove any +# provider must not be changed, or the pool will no longer work. Make sure you remove any # pools before removing or changing a provider. [[provider]] # An arbitrary string describing this provider. name = "lxd_local" - # Provider type. Garm is designed to allow creating providers which are used to spin + # Provider type. GARM is designed to allow creating providers which are used to spin # up compute resources, which in turn will run the github runner software. - # Currently, LXD is the only supported provider, but more will be written in the future. + # Currently, LXD is the only supprted provider, but more will be written in the future. provider_type = "lxd" # A short description of this provider. The name, description and provider types will # be included in the information returned by the API when listing available providers. description = "Local LXD installation" [provider.lxd] - # the path to the unix socket that LXD is listening on. This works if garm and LXD + # the path to the unix socket that LXD is listening on. This works if GARM and LXD # are on the same system, and this option takes precedence over the "url" option, # which connects over the network. unix_socket_path = "/var/snap/lxd/common/lxd/unix.socket" @@ -39,6 +42,14 @@ Garm leverages the virtual machines feature of LXD to create the runners. Here i # This option allows you to inject the "default" profile along with the profile selected # by the flavor. include_default_profile = false + # instance_type defines the type of instances this provider will create. + # + # Options are: + # + # * virtual-machine (default) + # * container + # + instance_type = "container" # enable/disable secure boot. If the image you select for the pool does not have a # signed bootloader, set this to false, otherwise your instances won't boot. secure_boot = false @@ -46,7 +57,7 @@ Garm leverages the virtual machines feature of LXD to create the runners. Here i project_name = "default" # URL is the address on which LXD listens for connections (ex: https://example.com:8443) url = "" - # garm supports certificate authentication for LXD remote connections. The easiest way + # GARM supports certificate authentication for LXD remote connections. The easiest way # to get the needed certificates, is to install the lxc client and add a remote. The # client_certificate, client_key and tls_server_certificate can be then fetched from # $HOME/snap/lxd/common/config. @@ -88,7 +99,7 @@ You can choose to connect to a local LXD server by using the ```unix_socket_path ### LXD remotes -By default, garm does not load any image remotes. You get to choose which remotes you add (if any). An image remote is a repository of images that LXD uses to create new instances, either virtual machines or containers. In the absence of any remote, garm will attempt to find the image you configure for a pool of runners, on the LXD server we're connecting to. If one is present, it will be used, otherwise it will fail and you will need to configure a remote. +By default, GARM does not load any image remotes. You get to choose which remotes you add (if any). An image remote is a repository of images that LXD uses to create new instances, either virtual machines or containers. In the absence of any remote, GARM will attempt to find the image you configure for a pool of runners, on the LXD server we're connecting to. If one is present, it will be used, otherwise it will fail and you will need to configure a remote. The sample config file in this repository has the usual default ```LXD``` remotes: @@ -100,20 +111,28 @@ When creating a new pool, you'll be able to specify which image you want to use. You can also create your own image remote, where you can host your own custom images. If you want to build your own images, have a look at [distrobuilder](https://github.com/lxc/distrobuilder). -Image remotes in the ```garm``` config, is a map of strings to remote settings. The name of the remote is the last bit of string in the section header. For example, the following section ```[provider.lxd.image_remotes.ubuntu_daily]```, defines the image remote named **ubuntu_daily**. Use this name to reference images inside that remote. +Image remotes in the ```GARM``` config, is a map of strings to remote settings. The name of the remote is the last bit of string in the section header. For example, the following section ```[provider.lxd.image_remotes.ubuntu_daily]```, defines the image remote named **ubuntu_daily**. Use this name to reference images inside that remote. -## The External provider +You can also use locally uploaded images. Check out the [performance considerations](./performance_considerations.md) page for details on how to customize local images and use them with GARM. + +### LXD Security considerations + +GARM does not apply any ACLs of any kind to the instances it creates. That task remains in the responsibility of the user. [Here is a guide for creating ACLs in LXD](https://linuxcontainers.org/lxd/docs/master/howto/network_acls/). You can of course use ```iptables``` or ```nftables``` to create any rules you wish. I recommend you create a separate isolated lxd bridge for runners, and secure it using ACLs/iptables/nftables. + +You must make sure that the code that runs as part of the workflows is trusted, and if that cannot be done, you must make sure that any malicious code that will be pulled in by the actions and run as part of a workload, is as contained as possible. There is a nice article about [securing your workflow runs here](https://blog.gitguardian.com/github-actions-security-cheat-sheet/). + +## External provider The external provider is a special kind of provider. It delegates the functionality needed to create the runners to external executables. These executables can be either binaries or scripts. As long as they adhere to the needed interface, they can be used to create runners in any target IaaS. This is identical to what ```containerd``` does with ```CNIs```. -There is currently one external provider for [OpenStack](https://www.openstack.org/) available in the [contrib folder of this repository](../contrib/providers.d/openstack). The provider is written in ```bash``` and it is just a sample. A production ready provider would need more error checking and idempotency, but it serves as an example of what can be done. As it stands, it is functional. +There are currently two sample external providers available in the [contrib folder of this repository](../contrib/providers.d/). The providers are written in ```bash``` and are meant as examples of how a provider could be written in ```bash```. Production ready providers would need more error checking and idempotency, but they serve as an example of what can be done. As it stands, they are functional. The configuration for an external provider is quite simple: ```toml # This is an example external provider. External providers are executables that # implement the needed interface to create/delete/list compute systems that are used -# by garm to create runners. +# by GARM to create runners. [[provider]] name = "openstack_external" description = "external openstack provider" @@ -127,13 +146,24 @@ provider_type = "external" provider_executable = "/etc/garm/providers.d/openstack/garm-external-provider" ``` -The external provider has three options: +The external provider has two options: * ```provider_executable``` * ```config_file``` -The ```provider_executable``` option is the absolute path to an executable that implements the provider logic. Garm will delegate all provider operations to this executable. This executable can be anything (bash, python, perl, go, etc). See [Writing an external provider](./external_provider.md) for more details. +The ```provider_executable``` option is the absolute path to an executable that implements the provider logic. GARM will delegate all provider operations to this executable. This executable can be anything (bash, python, perl, go, etc). See [Writing an external provider](./external_provider.md) for more details. + +The ```config_file``` option is a path on disk to an arbitrary file, that is passed to the external executable via the environment variable ```GARM_PROVIDER_CONFIG_FILE```. This file is only relevant to the external provider. GARM itself does not read it. In the case of the sample OpenStack provider, this file contains access information for an OpenStack cloud (what you would typically find in a ```keystonerc``` file) as well as some provider specific options like whether or not to boot from volume and which tenant network to use. You can check out the [sample config file](../contrib/providers.d/openstack/keystonerc) in this repository. + +If you want to implement an external provider, you can use this file for anything you need to pass into the binary when ```GARM``` calls it to execute a particular operation. + +### Available external providers + +For non testing purposes, there are two external providers currently available: + +* [OpenStack](https://github.com/cloudbase/garm-provider-openstack) +* [Azure](https://github.com/cloudbase/garm-provider-azure) -The ```config_file``` option is a path on disk to an arbitrary file, that is passed to the external executable via the environment variable ```GARM_PROVIDER_CONFIG_FILE```. This file is only relevant to the external provider. Garm itself does not read it. In the case of the OpenStack provider, this file contains access information for an OpenStack cloud (what you would typically find in a ```keystonerc``` file) as well as some provider specific options like whether or not to boot from volume and which tenant network to use. You can check out the [sample config file](../contrib/providers.d/openstack/keystonerc) in this repository. +Details on how to install and configure them are available in their respective repositories. -If you want to implement an external provider, you can use this file for anything you need to pass into the binary when ```garm``` calls it to execute a particular operation. +If you wrote a provider and would like to add it to the above list, feel free to open a PR. diff --git a/doc/quickstart.md b/doc/quickstart.md new file mode 100644 index 00000000..23fc89b7 --- /dev/null +++ b/doc/quickstart.md @@ -0,0 +1,551 @@ +# Quick start + +Okay, I lied. It's not that quick. But it's not that long either. I promise. + +In this guide I'm going to take you through the entire process of setting up garm from scratch. This will include editing the config file (which will probably take the longest amount of time), fetching a proper [PAT](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token) (personal access token) from GitHub, setting up the webhooks endpoint, defining your repo/org/enterprise and finally setting up a runner pool. + +For the sake of this guide, we'll assume you have access to the following setup: + +* A linux machine (ARM64 or AMD64) +* Optionally, docker/podman installed on that machine +* A public IP address or port forwarding set up on your router for port `80` or `443`. You can forward any ports, we just need to remember to use the same ports when we define the webhook in github, and the two URLs in the config file (more on that later). For the sake of this guide, I will assume you have port `80` or `443` forwarded to your machine. +* An `A` record pointing to your public IP address (optional, but recommended). Alternatively, you can use the IP address directly. I will use `garm.example.com` in this guide. If you'll be using an IP address, just replace `garm.example.com` with your IP address throughout this guide. +* All config files and data will be stored in `/etc/garm`. +* A [Personal Access Token (PAT)](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token) + +Why the need to expose GARM to the internet? Well, GARM uses webhooks sent by GitHub to automatically scale runners. Whenever a new job starts, a webhook is generated letting GARM know that there is a need for a runner. GARM then spins up a new runner instance and registers it with GitHub. When the job is done, the runner instance is automatically removed. This workflow is enabled by webhooks. + +## The GitHub PAT (Personal Access Token) + +Let's start by fetching a PAT so we get that out of the way. You can use the [GitHub docs](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token) to create a PAT. + +For a `classic` PAT, GARM needs the following permissions to function properly (depending on the hierarchy level you want to manage): + +* ```public_repo``` - for access to a repository +* ```repo``` - for access to a private repository +* ```admin:org``` - if you plan on using this with an organization to which you have access +* ```manage_runners:enterprise``` - if you plan to use garm at the enterprise level + +This doc will be updated at a future date with the exact permissions needed in case you want to use a fine grained PAT. + +## Create the config folder + +All of our config files and data will be stored in `/etc/garm`. Let's create that folder: + +```bash +sudo mkdir -p /etc/garm +``` + +Coincidentally, this is also where the docker container [looks for the config](../Dockerfile#L29) when it starts up. You can either use `Docker` or you can set up garm directly on your system. I'll show you both ways. In both cases, we need to first create the config folder and a proper config file. + +## The config file + +There is a full config file, with detailed comments for each option, in the [testdata folder](../testdata/config.toml). You can use that as a reference. But for the purposes of this guide, we'll be using a minimal config file and add things on as we proceed. + +Open `/etc/garm/config.toml` in your favorite editor and paste the following: + +```toml +[default] +callback_url = "https://garm.example.com/api/v1/callbacks/status" +metadata_url = "https://garm.example.com/api/v1/metadata" + +[metrics] +enable = true +disable_auth = false + +[jwt_auth] +# Obviously, this needs to be changed :). +secret = ")9gk_4A6KrXz9D2u`0@MPea*sd6W`%@5MAWpWWJ3P3EqW~qB!!(Vd$FhNc*eU4vG" +time_to_live = "8760h" + +[apiserver] + bind = "0.0.0.0" + port = 80 + use_tls = false + +[database] + backend = "sqlite3" + # This needs to be changed. + passphrase = "shreotsinWadquidAitNefayctowUrph" + [database.sqlite3] + db_file = "/etc/garm/garm.db" +``` + +This is a minimal config, with no providers or credentials defined. In this example we have the [default](./config_default.md), [metrics](./config_metrics.md), [jwt_auth](./config_jwt_auth.md), [apiserver](./config_api_server.md) and [database](./config_database.md) sections. Each are documented separately. Feel free to read through the available docs if, for example you need to enable TLS without using an nginx reverse proxy or if you want to enable the debug server, the log streamer or a log file. + +In this sample config we: + +* define the callback and the metadata URLs +* enable metrics with authentication +* set a JWT secret which is used to sign JWT tokens +* set a time to live for the JWT tokens +* enable the API server on port `80` and bind it to all interfaces +* set the database backend to `sqlite3` and set a passphrase for sealing secrets (just webhook secrets for now) + +The callback URLs are really important and need to point back to garm. You will notice that the domain name used in these options, is the same one we defined at the beginning of this guide. If you won't use a domain name, replace `garm.example.com` with your IP address and port number. + +We need to tell garm by which addresses it can be reached. There are many ways by which GARMs API endpoints can be exposed, and there is no sane way in which GARM itself can determine if it's behind a reverse proxy or not. The metadata URL may be served by a reverse proxy with a completely different domain name than the callback URL. Both domains pointing to the same installation of GARM in the end. + +The information in these two options is used by the instances we spin up to phone home their status and to fetch the needed metadata to finish setting themselves up. For now, the metadata URL is only used to fetch the runner registration token. + +We won't go too much into detail about each of the options here. Have a look at the different config sections and their respective docs for more information. + +At this point, we have a valid config file, but we still need to add `provider` and `credentials` sections. + +## The provider section + +This is where you have a decision to make. GARM has a number of providers you can leverage. At the time of this writing, we have support for: + +* LXD +* Azure +* OpenStack + +The LXD provider is built into GARM itself and has no external requirements. The [Azure](https://github.com/cloudbase/garm-provider-azure) and [OpenStack](https://github.com/cloudbase/garm-provider-openstack) ones are `external` providers in the form of an executable that GARM calls into. + +Both the LXD and the external provider configs are [documented in a separate doc](./providers.md). + +The easiest provider to set up is probably the LXD provider. You don't need an account on an external cloud. You can just use your machine. + +You will need to have LXD installed and configured. There is an excellent [getting started guide](https://documentation.ubuntu.com/lxd/en/latest/getting_started/) for LXD. Follow the instructions there to install and configure LXD, then come back here. + +Once you have LXD installed and configured, you can add the provider section to your config file. If you're connecting to the `local` LXD installation, the [config snippet for the LXD provider](./providers.md#lxd-provider) will work out of the box. We'll be connecting using the unix socket so no further configuration will be needed. + +Go ahead and copy and paste that entire snippet in your GARM config file (`/etc/garm/config.toml`). + +You can also use an external provider instead of LXD. You will need to define the provider section in your config file and point it to the executable and the provider config file. The [config snippet for the external provider](./providers.md#external-provider) gives you an example of how that can be done. Configuring the external provider is outside the scope of this guide. You will need to consult the documentation for the external provider you want to use. + +## The credentials section + +The credentials section is where we define out GitHub credentials. GARM is capable of using either GitHub proper or [GitHub Enterprise Server](https://docs.github.com/en/enterprise-server@3.6/get-started/onboarding/getting-started-with-github-enterprise-server). The credentials section allows you to override the default GitHub API endpoint and point it to your own deployment of GHES. + +The credentials section is [documented in a separate doc](./github_credentials.md), but we will include a small snippet here for clarity. + +```toml +# This is a list of credentials that you can define as part of the repository +# or organization definitions. They are not saved inside the database, as there +# is no Vault integration (yet). This will change in the future. +# Credentials defined here can be listed using the API. Obviously, only the name +# and descriptions are returned. +[[github]] + name = "gabriel" + description = "github token for user gabriel" + # This is a personal token with access to the repositories and organizations + # you plan on adding to garm. The "workflow" option needs to be selected in order + # to work with repositories, and the admin:org needs to be set if you plan on + # adding an organization. + oauth2_token = "super secret token" +``` + +The `oauth2_token` option will hold the PAT we created earlier. You can add multiple credentials to the config file. Each will be referenced by name when we define the repo/org/enterprise. + +Alright, we're almost there. We have a config file with a provider and a credentials section. We now have to start the service and create a webhook in GitHub pointing at our `webhook` endpoint. + +## Starting the service + +You can start GARM using docker or directly on your system. I'll show you both ways. + +### Using Docker + +If you're using docker, you can start the service with: + +```bash +docker run -d \ + --name garm \ + -p 80:80 \ + -v /etc/garm:/etc/garm:rw \ + -v /var/snap/lxd/common/lxd/unix.socket:/var/snap/lxd/common/lxd/unix.socket:rw \ + ghcr.io/cloudbase/garm:v0.1.2 +``` + +You will notice we also mounted the LXD unix socket from the host inside the container where the config you pasted expects to find it. If you plan to use an external provider that does not need to connect to LXD over a unix socket, feel free to remove that mount. + +Check the logs to make sure everything is working as expected: + +```bash +ubuntu@garm:~$ docker logs garm +signal.NotifyContext(context.Background, [interrupt terminated]) +2023/07/17 21:55:43 Loading provider lxd_local +2023/07/17 21:55:43 registering prometheus metrics collectors +2023/07/17 21:55:43 setting up metric routes +``` + +### Setting up GARM as a system service + +This process is a bit more involved. We'll need to create a new user for garm and set up permissions for that user to connect to LXD. + +First, create the user: + +```bash +useradd --shell /usr/bin/false \ + --system \ + --groups lxd \ + --no-create-home garm +``` + +Adding the `garm` user to the LXD group will allow it to connect to the LXD unix socket. We'll need that considering the config we crafted above. + +Next, download the latest release from the [releases page](https://github.com/cloudbase/garm/releases). + +```bash +wget -q -O - https://github.com/cloudbase/garm/releases/download/v0.1.2/garm-linux-amd64.tgz | tar xzf - -C /usr/local/bin/ +``` + +We'll be running under an unprivileged user. If we want to be able to listen on any port under `1024`, we'll have to set some capabilities on the binary: + +```bash +setcap cap_net_bind_service=+ep /usr/local/bin/garm +``` + +Change the permissions on the config dir: + +```bash +chown -R garm:garm /etc/garm +``` + +Copy the sample `systemd` service file: + +```bash +wget -O /etc/systemd/system/garm.service \ + https://raw.githubusercontent.com/cloudbase/garm/v0.1.2/contrib/garm.service +``` + +Reload the `systemd` daemon and start the service: + +```bash +systemctl daemon-reload +systemctl start garm +``` + +Check the logs to make sure everything is working as expected: + +```bash +ubuntu@garm:~$ sudo journalctl -u garm +``` + +Check that you can make a request to the API: + +```bash +ubuntu@garm:~$ curl http://garm.example.com/webhooks +ubuntu@garm:~$ docker logs garm +signal.NotifyContext(context.Background, [interrupt terminated]) +2023/07/17 22:21:33 Loading provider lxd_local +2023/07/17 22:21:33 registering prometheus metrics collectors +2023/07/17 22:21:33 setting up metric routes +2023/07/17 22:21:35 ignoring unknown event +172.17.0.1 - - [17/Jul/2023:22:21:35 +0000] "GET /webhooks HTTP/1.1" 200 0 "" "curl/7.81.0" +``` + +Excellent! We have a working GARM installation. Now we need to set up the webhook in GitHub. + +## Setting up the webhook + +Before we create a pool, we need to set up the webhook in GitHub. This is a fairly simple process. + +Head over to the [webhooks doc](./webhooks.md) and follow the instructions there. Come back here when you're done. + +After you've finished setting up the webhook, there are just a few more things to do: + +* Initialize GARM +* Add a repo/org/enterprise +* Create a pool + +## Initializing GARM + +Before we can start using GARM, we need initialize it. This will create the `admin` user and generate a unique controller ID that will identify this GARM installation. This process allows us to use multiple GARM installations with the same GitHub account. GARM will use the controller ID to identify the runners it creates. This way we won't run the risk of accidentally removing runners we don't manage. + +To initialize GARM, we'll use the `garm-cli` tool. You can download the latest release from the [releases page](https://github.com/cloudbase/garm/releases): + +```bash +wget -q -O - https://github.com/cloudbase/garm/releases/download/v0.1.2/garm-cli-linux-amd64.tgz | tar xzf - -C /usr/local/bin/ +``` + +Now we can initialize GARM: + +```bash +ubuntu@garm:~$ garm-cli init --name="local_garm" --url https://garm.example.com +Username: admin +Email: root@localhost +✔ Password: ************* ++----------+--------------------------------------+ +| FIELD | VALUE | ++----------+--------------------------------------+ +| ID | ef4ab6fd-1252-4d5a-ba5a-8e8bd01610ae | +| Username | admin | +| Email | root@localhost | +| Enabled | true | ++----------+--------------------------------------+ +``` + +The init command also created a local CLI profile for your new GARM server: + +```bash +ubuntu@garm:~$ garm-cli profile list ++----------------------+--------------------------+ +| NAME | BASE URL | ++----------------------+--------------------------+ +| local_garm (current) | https://garm.example.com | ++----------------------+--------------------------+ +``` + +Every time you init a new GARM instance, a new profile will be created in your local `garm-cli` config. You can also log into an already initialized instance using: + +```bash +garm-cli profile add --name="another_garm" --url https://garm2.example.com +``` + +Then you can switch between profiles using: + +```bash +garm-cli profile switch another_garm +``` + +## Define a repo + +We now have a working GARM installation, with github credentials and a provider added. It's time to add a repo. + +Before we add a repo, let's list credentials. We'll need their names when we'll add a new repo. + +```bash +gabriel@rossak:~$ garm-cli credentials list ++---------+-------------------------------+--------------------+-------------------------+-----------------------------+ +| NAME | DESCRIPTION | BASE URL | API URL | UPLOAD URL | ++---------+-------------------------------+--------------------+-------------------------+-----------------------------+ +| gabriel | github token for user gabriel | https://github.com | https://api.github.com/ | https://uploads.github.com/ | ++---------+-------------------------------+--------------------+-------------------------+-----------------------------+ +``` + +Even though you didn't explicitly set the URLs, GARM will default to the GitHub ones. You can override them if you want to use a GHES deployment. + +Now we can add a repo: + +```bash +garm-cli repo add \ + --credentials gabriel \ + --owner gsamfira \ + --name scripts \ + --webhook-secret $SECRET +``` + +In this case, `$SECRET` holds the webhook secret you set previously when you defined the webhook in GitHub. This secret is mandatory as GARM will always validate the webhook payloads it receives. + +You should see something like this: + +```bash +gabriel@rossak:~$ garm-cli repo add \ +> --credentials gabriel \ +> --owner gsamfira \ +> --name scripts \ +> --webhook-secret $SECRET ++----------------------+--------------------------------------+ +| FIELD | VALUE | ++----------------------+--------------------------------------+ +| ID | f4900c7c-2ec0-41bd-9eab-d70fe9bd850d | +| Owner | gsamfira | +| Name | scripts | +| Credentials | gabriel | +| Pool manager running | false | +| Failure reason | | ++----------------------+--------------------------------------+ +``` + +We can now list the repos: + +```bash +gabriel@rock:~$ garm-cli repo ls ++--------------------------------------+----------+---------+------------------+------------------+ +| ID | OWNER | NAME | CREDENTIALS NAME | POOL MGR RUNNING | ++--------------------------------------+----------+---------+------------------+------------------+ +| f4900c7c-2ec0-41bd-9eab-d70fe9bd850d | gsamfira | scripts | gabriel | true | ++--------------------------------------+----------+---------+------------------+------------------+ +``` + +Excellent! Make a note of the ID. We'll need it later when we create a pool. + +## Create a pool + +This is the last step. You're almost there! + +To create a pool we'll need the repo ID from the previous step (which we have) and a provider in which the pool will spin up new runners. We'll use the LXD provider we defined earlier, but we need its name: + +```bash +gabriel@rossak:~$ garm-cli provider list ++-----------+------------------------+------+ +| NAME | DESCRIPTION | TYPE | ++-----------+------------------------+------+ +| lxd_local | Local LXD installation | lxd | ++-----------+------------------------+------+ +``` + +Now we can create a pool: + +```bash +garm-cli pool add \ + --repo f4900c7c-2ec0-41bd-9eab-d70fe9bd850d \ + --enabled true \ + --provider-name lxd_local \ + --flavor default \ + --image ubuntu:22.04 \ + --max-runners 5 \ + --min-idle-runners 0 \ + --os-arch amd64 \ + --os-type linux \ + --tags ubuntu,generic +``` + +You should see something like this: + +```bash +gabriel@rossak:~$ garm-cli pool add \ +> --repo f4900c7c-2ec0-41bd-9eab-d70fe9bd850d \ +> --enabled true \ +> --provider-name lxd_local \ +> --flavor default \ +> --image ubuntu:22.04 \ +> --max-runners 5 \ +> --min-idle-runners 0 \ +> --os-arch amd64 \ +> --os-type linux \ +> --tags ubuntu,generic ++--------------------------+--------------------------------------------+ +| FIELD | VALUE | ++--------------------------+--------------------------------------------+ +| ID | 344e4a72-2035-4a18-a3d5-87bd3874b56c | +| Provider Name | lxd_local | +| Image | ubuntu:22.04 | +| Flavor | default | +| OS Type | linux | +| OS Architecture | amd64 | +| Max Runners | 5 | +| Min Idle Runners | 0 | +| Runner Bootstrap Timeout | 20 | +| Tags | self-hosted, amd64, Linux, ubuntu, generic | +| Belongs to | gsamfira/scripts | +| Level | repo | +| Enabled | true | +| Runner Prefix | garm | +| Extra specs | | +| GitHub Runner Group | | ++--------------------------+--------------------------------------------+ +``` + +If we list the pool we should see it: + +```bash +gabriel@rock:~$ garm-cli pool ls -a ++--------------------------------------+--------------+---------+----------------------------------------+------------------+-------+---------+---------------+ +| ID | IMAGE | FLAVOR | TAGS | BELONGS TO | LEVEL | ENABLED | RUNNER PREFIX | ++--------------------------------------+--------------+---------+----------------------------------------+------------------+-------+---------+---------------+ +| 344e4a72-2035-4a18-a3d5-87bd3874b56c | ubuntu:22.04 | default | self-hosted amd64 Linux ubuntu generic | gsamfira/scripts | repo | true | garm | ++--------------------------------------+--------------+---------+----------------------------------------+------------------+-------+---------+---------------+ +``` + +This pool is enabled, but the `min-idle-runners` option is set to 0. This means that it will not create any lingering runners. It will only create runners when a job is started. If your provider is slow to boot up new instances, you may want to set this to a value higher than 0. + +For the purposes of this guide, we'll increase it to 1 so we have a runner created. + +First, list current runners: + +```bash +gabriel@rossak:~$ garm-cli runner ls -a ++----+------+--------+---------------+---------+ +| NR | NAME | STATUS | RUNNER STATUS | POOL ID | ++----+------+--------+---------------+---------+ ++----+------+--------+---------------+---------+ +``` + +No runners. Now, let's update the pool and set `min-idle-runners` to 1: + +```bash +gabriel@rossak:~$ garm-cli pool update 344e4a72-2035-4a18-a3d5-87bd3874b56c --min-idle-runners=1 ++--------------------------+--------------------------------------------+ +| FIELD | VALUE | ++--------------------------+--------------------------------------------+ +| ID | 344e4a72-2035-4a18-a3d5-87bd3874b56c | +| Provider Name | lxd_local | +| Image | ubuntu:22.04 | +| Flavor | default | +| OS Type | linux | +| OS Architecture | amd64 | +| Max Runners | 5 | +| Min Idle Runners | 1 | +| Runner Bootstrap Timeout | 20 | +| Tags | self-hosted, amd64, Linux, ubuntu, generic | +| Belongs to | gsamfira/scripts | +| Level | repo | +| Enabled | true | +| Runner Prefix | garm | +| Extra specs | | +| GitHub Runner Group | | ++--------------------------+--------------------------------------------+ +``` + +Now if we list the runners: + +```bash +gabriel@rossak:~$ garm-cli runner ls -a ++----+-------------------+----------------+---------------+--------------------------------------+ +| NR | NAME | STATUS | RUNNER STATUS | POOL ID | ++----+-------------------+----------------+---------------+--------------------------------------+ +| 1 | garm-tdtD6zpsXhj1 | pending_create | pending | 344e4a72-2035-4a18-a3d5-87bd3874b56c | ++----+-------------------+----------------+---------------+--------------------------------------+ +``` + +If we check our LXD, we should also see it there as well: + +```bash +gabriel@rossak:~$ lxc list ++-------------------+---------+---------------------+------+-----------+-----------+ +| NAME | STATE | IPV4 | IPV6 | TYPE | SNAPSHOTS | ++-------------------+---------+---------------------+------+-----------+-----------+ +| garm-tdtD6zpsXhj1 | RUNNING | 10.44.30.155 (eth0) | | CONTAINER | 0 | ++-------------------+---------+---------------------+------+-----------+-----------+ +``` + +If we wait for a bit and run: + +```bash +gabriel@rossak:~$ garm-cli runner show garm-tdtD6zpsXhj1 ++-----------------+------------------------------------------------------------------------------------------------------+ +| FIELD | VALUE | ++-----------------+------------------------------------------------------------------------------------------------------+ +| ID | 7ac024c9-1854-4911-9859-d061059244a6 | +| Provider ID | garm-tdtD6zpsXhj1 | +| Name | garm-tdtD6zpsXhj1 | +| OS Type | linux | +| OS Architecture | amd64 | +| OS Name | ubuntu | +| OS Version | jammy | +| Status | running | +| Runner Status | idle | +| Pool ID | 344e4a72-2035-4a18-a3d5-87bd3874b56c | +| Addresses | 10.44.30.155 | +| Status Updates | 2023-07-18T14:32:26: runner registration token was retrieved | +| | 2023-07-18T14:32:26: downloading tools from https://github.com/actions/runner/releases/download/v2.3 | +| | 06.0/actions-runner-linux-amd64-2.306.0.tar.gz | +| | 2023-07-18T14:32:30: extracting runner | +| | 2023-07-18T14:32:36: installing dependencies | +| | 2023-07-18T14:33:03: configuring runner | +| | 2023-07-18T14:33:14: runner successfully configured after 1 attempt(s) | +| | 2023-07-18T14:33:14: installing runner service | +| | 2023-07-18T14:33:15: starting service | +| | 2023-07-18T14:33:16: runner successfully installed | ++-----------------+------------------------------------------------------------------------------------------------------+ +``` + +We can see the runner getting installed and phoning home with status updates. You should now see it in your GitHub repo under `Settings --> Actions --> Runners`. + +You can also target this runner using one or more of its labels. In this case, we can target it using `ubuntu` or `generic`. + +You can also view jobs sent to your garm instance using the `garm-cli job ls` command: + +```bash +gabriel@rossak:~$ garm-cli job ls ++----+------+--------+------------+-------------+------------+------------------+-----------+ +| ID | NAME | STATUS | CONCLUSION | RUNNER NAME | REPOSITORY | REQUESTED LABELS | LOCKED BY | ++----+------+--------+------------+-------------+------------+------------------+-----------+ ++----+------+--------+------------+-------------+------------+------------------+-----------+ +``` + +There are no jobs sent yet to my GARM install, but once you start sending jobs, you'll see them here as well. + +That's it! You now have a working GARM installation. You can add more repos, orgs or enterprises and create more pools. You can also add more providers for different clouds and credentials with access to different GitHub resources. diff --git a/doc/running_garm.md b/doc/running_garm.md deleted file mode 100644 index 4ac623b8..00000000 --- a/doc/running_garm.md +++ /dev/null @@ -1,391 +0,0 @@ -# Running garm - -Create a folder for the config: - - ```bash - mkdir $HOME/garm - ``` - -Create a config file for ```garm```: - - ```bash - cp ./testdata/config.toml $HOME/garm/config.toml - ``` - -Customize the config whichever way you want, then run ```garm```: - - ```bash - garm -config $HOME/garm/config.toml - ``` - -This will start the API and migrate the database. Note, if you're using MySQL, you will need to create a database, grant access to a user and configure those credentials in the ```config.toml``` file. - -## First run - -Before you can use ```garm```, you need to initialize it. This means we need to create an admin user, and login: - - ```bash - ubuntu@experiments:~$ garm-cli init --name="local_garm" --url https://garm.example.com - Username: admin - Email: root@localhost - ✔ Password: *************█ - +----------+--------------------------------------+ - | FIELD | VALUE | - +----------+--------------------------------------+ - | ID | ef4ab6fd-1252-4d5a-ba5a-8e8bd01610ae | - | Username | admin | - | Email | root@localhost | - | Enabled | true | - +----------+--------------------------------------+ - ``` - -Alternatively you can run this in non-interactive mode. See ```garm-cli init -h``` for details. - -## Enabling bash completion - -Before we begin, let's make our lives a little easier and set up bash completion. The wonderful [cobra](https://github.com/spf13/cobra) library gives us completion for free: - - ```bash - mkdir $HOME/.bash_completion.d - echo 'source $HOME/.bash_completion.d/* >/dev/null 2>&1|| true' >> $HOME/.bash_completion - ``` - -Now generate the completion file: - - ```bash - garm-cli completion bash > $HOME/.bash_completion.d/garm - ``` - -Completion for multiple shells is available: - - ```bash - ubuntu@experiments:~$ garm-cli completion - Generate the autocompletion script for garm-cli for the specified shell. - See each sub-command's help for details on how to use the generated script. - - Usage: - garm-cli completion [command] - - Available Commands: - bash Generate the autocompletion script for bash - fish Generate the autocompletion script for fish - powershell Generate the autocompletion script for powershell - zsh Generate the autocompletion script for zsh - - Flags: - -h, --help help for completion - - Global Flags: - --debug Enable debug on all API calls - - Use "garm-cli completion [command] --help" for more information about a command. - ``` - -## Adding a repository/organization/enterprise - -To add a repository, we need credentials. Let's list the available credentials currently configured. These credentials are added to ```garm``` using the config file (see above), but we need to reference them by name when creating a repo. - - ```bash - ubuntu@experiments:~$ garm-cli credentials list - +---------+------------------------------+ - | NAME | DESCRIPTION | - +---------+------------------------------+ - | gabriel | github token or user gabriel | - +---------+------------------------------+ - ``` - -Now we can add a repository to ```garm```: - - ```bash - ubuntu@experiments:~$ garm-cli repository create \ - --credentials=gabriel \ - --owner=gabriel-samfira \ - --name=scripts \ - --webhook-secret="super secret webhook secret you configured in github webhooks" - +-------------+--------------------------------------+ - | FIELD | VALUE | - +-------------+--------------------------------------+ - | ID | 77258e1b-81d2-4821-bdd7-f6923a026455 | - | Owner | gabriel-samfira | - | Name | scripts | - | Credentials | gabriel | - +-------------+--------------------------------------+ - ``` - -To add an organization, use the following command: - - ```bash - ubuntu@experiments:~$ garm-cli organization create \ - --credentials=gabriel \ - --name=gsamfira \ - --webhook-secret="$SECRET" - +-------------+--------------------------------------+ - | FIELD | VALUE | - +-------------+--------------------------------------+ - | ID | 7f0b83d5-3dc0-42de-b189-f9bbf1ae8901 | - | Name | gsamfira | - | Credentials | gabriel | - +-------------+--------------------------------------+ - ``` - -To add an enterprise, use the following command: - - ```bash - ubuntu@experiments:~$ garm-cli enterprise create \ - --credentials=gabriel \ - --name=gsamfira \ - --webhook-secret="$SECRET" - +-------------+--------------------------------------+ - | FIELD | VALUE | - +-------------+--------------------------------------+ - | ID | 0925033b-049f-4334-a460-c26f979d2356 | - | Name | gsamfira | - | Credentials | gabriel | - +-------------+--------------------------------------+ - ``` - -## Creating a pool - -Pools are objects that define one type of worker and rules by which that pool of workers will be maintained. You can have multiple pools of different types of instances. Each pool can have different images, be on different providers and have different tags. - -Before we can create a pool, we need to list the available providers. Providers are defined in the config (see above), but we need to reference them by name in the pool. - - ```bash - ubuntu@experiments:~$ garm-cli provider list - +-----------+------------------------+------+ - | NAME | DESCRIPTION | TYPE | - +-----------+------------------------+------+ - | lxd_local | Local LXD installation | lxd | - +-----------+------------------------+------+ - ``` - -Now we can create a pool for repo ```gabriel-samfira/scripts```: - - ```bash - ubuntu@experiments:~$ garm-cli pool add \ - --repo=77258e1b-81d2-4821-bdd7-f6923a026455 \ - --flavor="default" \ - --image="ubuntu:20.04" \ - --provider-name="lxd_local" \ - --tags="ubuntu,simple-runner,repo-runner" \ - --enabled=false - +------------------+-------------------------------------------------------------+ - | FIELD | VALUE | - +------------------+-------------------------------------------------------------+ - | ID | fb25f308-7ad2-4769-988e-6ec2935f642a | - | Provider Name | lxd_local | - | Image | ubuntu:20.04 | - | Flavor | default | - | OS Type | linux | - | OS Architecture | amd64 | - | Max Runners | 5 | - | Min Idle Runners | 1 | - | Tags | ubuntu, simple-runner, repo-runner, self-hosted, x64, linux | - | Belongs to | gabriel-samfira/scripts | - | Level | repo | - | Enabled | false | - +------------------+-------------------------------------------------------------+ - ``` - -There are a bunch of things going on here, so let's break it down. We created a pool for repo ```gabriel-samfira/scripts``` (identified by the ID ```77258e1b-81d2-4821-bdd7-f6923a026455```). This pool has the following characteristics: - -* flavor=default - The **flavor** describes the hardware aspects of an instance. In LXD terms, this translates to [profiles](https://linuxcontainers.org/lxd/docs/master/profiles/). In LXD, profiles describe how much memory, CPU, NICs and disks a particular instance will get. Much like the flavors in OpenStack or any public cloud provider -* image=ubuntu:20.04 - The image describes the operating system that will be spun up on the provider. LXD fetches these images from one of the configured remotes, or from the locally cached images. On AWS, this would be an AMI (for example). -* provider-name=lxd_local - This is the provider on which we'll be spinning up runners. You can have as many providers defined as you wish, and you can reference either one of them when creating a pool. -* tags="ubuntu,simple-runner,repo-runner" - This list of tags will be added to all runners maintained by this pool. These are the tags you can use to target these runners in your workflows. By default, the github runner will automatically add a few default tags (self-hosted, x64, linux in the above example) -* enabled=false - This option creates the pool in **disabled** state. When disabled, no new runners will be spun up. - -By default, a pool is created with a max worker count of ```5``` and a minimum idle runner count of ```1```. This means that this pool will create by default one runner, and will automatically add more, as jobs are triggered on github. The idea is to have at least one runner ready to accept a workflow job. The pool will keep adding workers until the max runner count is reached. Once a workflow job is complete, the runner is automatically deleted, and replaced. - -To update the pool, we cam use the following command: - - ```bash - ubuntu@experiments:~$ garm-cli pool update fb25f308-7ad2-4769-988e-6ec2935f642a --enabled=true - +------------------+-------------------------------------------------------------+ - | FIELD | VALUE | - +------------------+-------------------------------------------------------------+ - | ID | fb25f308-7ad2-4769-988e-6ec2935f642a | - | Provider Name | lxd_local | - | Image | ubuntu:20.04 | - | Flavor | default | - | OS Type | linux | - | OS Architecture | amd64 | - | Max Runners | 5 | - | Min Idle Runners | 1 | - | Tags | ubuntu, simple-runner, repo-runner, self-hosted, x64, linux | - | Belongs to | gabriel-samfira/scripts | - | Level | repo | - | Enabled | true | - +------------------+-------------------------------------------------------------+ - ``` - -Now, if we list the runners, we should see one being created: - - ```bash - ubuntu@experiments:~$ garm-cli runner ls fb25f308-7ad2-4769-988e-6ec2935f642a - +-------------------------------------------+----------------+---------------+--------------------------------------+ - | NAME | STATUS | RUNNER STATUS | POOL ID | - +-------------------------------------------+----------------+---------------+--------------------------------------+ - | garm-edeb8f46-ab09-4ed9-88fc-2731ecf9aabe | pending_create | pending | fb25f308-7ad2-4769-988e-6ec2935f642a | - +-------------------------------------------+----------------+---------------+--------------------------------------+ - ``` - -We can also do a show on that runner to get more info: - - ```bash - ubuntu@experiments:~$ garm-cli runner show garm-edeb8f46-ab09-4ed9-88fc-2731ecf9aabe - +-----------------+-------------------------------------------+ - | FIELD | VALUE | - +-----------------+-------------------------------------------+ - | ID | 089d63c9-5567-4318-a3a6-e065685c975b | - | Provider ID | garm-edeb8f46-ab09-4ed9-88fc-2731ecf9aabe | - | Name | garm-edeb8f46-ab09-4ed9-88fc-2731ecf9aabe | - | OS Type | linux | - | OS Architecture | amd64 | - | OS Name | ubuntu | - | OS Version | focal | - | Status | running | - | Runner Status | pending | - | Pool ID | fb25f308-7ad2-4769-988e-6ec2935f642a | - +-----------------+-------------------------------------------+ - ``` - -If we check out LXD, we can see the instance was created and is currently being bootstrapped: - - ```bash - ubuntu@experiments:~$ lxc list - +-------------------------------------------+---------+-------------------------+------+-----------------+-----------+ - | NAME | STATE | IPV4 | IPV6 | TYPE | SNAPSHOTS | - +-------------------------------------------+---------+-------------------------+------+-----------------+-----------+ - | garm-edeb8f46-ab09-4ed9-88fc-2731ecf9aabe | RUNNING | 10.247.246.219 (enp5s0) | | VIRTUAL-MACHINE | 0 | - +-------------------------------------------+---------+-------------------------+------+-----------------+-----------+ - ``` - -It might take a couple of minutes for the runner to come online, as the instance will do a full upgrade, then download the runner and install it. But once the installation is done you should see something like this: - - ```bash - ubuntu@experiments:~$ garm-cli runner show garm-edeb8f46-ab09-4ed9-88fc-2731ecf9aabe - +-----------------+--------------------------------------------------------------------------------------------------------------------------------------------------+ - | FIELD | VALUE | - +-----------------+--------------------------------------------------------------------------------------------------------------------------------------------------+ - | ID | 089d63c9-5567-4318-a3a6-e065685c975b | - | Provider ID | garm-edeb8f46-ab09-4ed9-88fc-2731ecf9aabe | - | Name | garm-edeb8f46-ab09-4ed9-88fc-2731ecf9aabe | - | OS Type | linux | - | OS Architecture | amd64 | - | OS Name | ubuntu | - | OS Version | focal | - | Status | running | - | Runner Status | idle | - | Pool ID | fb25f308-7ad2-4769-988e-6ec2935f642a | - | Status Updates | 2022-05-06T13:21:54: downloading tools from https://github.com/actions/runner/releases/download/v2.291.1/actions-runner-linux-x64-2.291.1.tar.gz | - | | 2022-05-06T13:21:56: extracting runner | - | | 2022-05-06T13:21:58: installing dependencies | - | | 2022-05-06T13:22:07: configuring runner | - | | 2022-05-06T13:22:12: installing runner service | - | | 2022-05-06T13:22:12: starting service | - | | 2022-05-06T13:22:13: runner successfully installed | - +-----------------+--------------------------------------------------------------------------------------------------------------------------------------------------+ - ``` - -If we list the runners for this pool, we should see one runner with a ```RUNNER STATUS``` of ```idle```: - - ```bash - ubuntu@experiments:~$ garm-cli runner ls fb25f308-7ad2-4769-988e-6ec2935f642a - +-------------------------------------------+---------+---------------+--------------------------------------+ - | NAME | STATUS | RUNNER STATUS | POOL ID | - +-------------------------------------------+---------+---------------+--------------------------------------+ - | garm-edeb8f46-ab09-4ed9-88fc-2731ecf9aabe | running | idle | fb25f308-7ad2-4769-988e-6ec2935f642a | - +-------------------------------------------+---------+---------------+--------------------------------------+ - ``` - -## Updating a pool - -Let's update the pool and request that it maintain a number of minimum idle runners equal to 3: - - ```bash - ubuntu@experiments:~$ garm-cli pool update fb25f308-7ad2-4769-988e-6ec2935f642a \ - --min-idle-runners=3 \ - --max-runners=10 - +------------------+----------------------------------------------------------------------------------+ - | FIELD | VALUE | - +------------------+----------------------------------------------------------------------------------+ - | ID | fb25f308-7ad2-4769-988e-6ec2935f642a | - | Provider Name | lxd_local | - | Image | ubuntu:20.04 | - | Flavor | default | - | OS Type | linux | - | OS Architecture | amd64 | - | Max Runners | 10 | - | Min Idle Runners | 3 | - | Tags | ubuntu, simple-runner, repo-runner, self-hosted, x64, linux | - | Belongs to | gabriel-samfira/scripts | - | Level | repo | - | Enabled | true | - | Instances | garm-edeb8f46-ab09-4ed9-88fc-2731ecf9aabe (089d63c9-5567-4318-a3a6-e065685c975b) | - +------------------+----------------------------------------------------------------------------------+ - ``` - -Now if we list runners we should see 2 more in ```pending``` state: - - ```bash - ubuntu@experiments:~$ garm-cli runner ls fb25f308-7ad2-4769-988e-6ec2935f642a - +-------------------------------------------+---------+---------------+--------------------------------------+ - | NAME | STATUS | RUNNER STATUS | POOL ID | - +-------------------------------------------+---------+---------------+--------------------------------------+ - | garm-edeb8f46-ab09-4ed9-88fc-2731ecf9aabe | running | idle | fb25f308-7ad2-4769-988e-6ec2935f642a | - +-------------------------------------------+---------+---------------+--------------------------------------+ - | garm-bc180c6c-6e31-4c7b-8ce1-da0ffd76e247 | running | pending | fb25f308-7ad2-4769-988e-6ec2935f642a | - +-------------------------------------------+---------+---------------+--------------------------------------+ - | garm-37c5daf4-18c5-47fc-95de-8c1656889093 | running | pending | fb25f308-7ad2-4769-988e-6ec2935f642a | - +-------------------------------------------+---------+---------------+--------------------------------------+ - ``` - -We can see them in LXC as well: - - ```bash - ubuntu@experiments:~$ lxc list - +-------------------------------------------+---------+-------------------------+------+-----------------+-----------+ - | NAME | STATE | IPV4 | IPV6 | TYPE | SNAPSHOTS | - +-------------------------------------------+---------+-------------------------+------+-----------------+-----------+ - | garm-37c5daf4-18c5-47fc-95de-8c1656889093 | RUNNING | | | VIRTUAL-MACHINE | 0 | - +-------------------------------------------+---------+-------------------------+------+-----------------+-----------+ - | garm-bc180c6c-6e31-4c7b-8ce1-da0ffd76e247 | RUNNING | | | VIRTUAL-MACHINE | 0 | - +-------------------------------------------+---------+-------------------------+------+-----------------+-----------+ - | garm-edeb8f46-ab09-4ed9-88fc-2731ecf9aabe | RUNNING | 10.247.246.219 (enp5s0) | | VIRTUAL-MACHINE | 0 | - +-------------------------------------------+---------+-------------------------+------+-----------------+-----------+ - ``` - -Once they transition to ```idle```, you should see them in your repo settings, under ```Actions --> Runners```. - -The procedure is identical for organizations. Have a look at the garm-cli help: - - ```bash - ubuntu@experiments:~$ garm-cli -h - CLI for the github self hosted runners manager. - - Usage: - garm-cli [command] - - Available Commands: - completion Generate the autocompletion script for the specified shell - credentials List configured credentials - debug-log Stream garm log - enterprise Manage enterprise - help Help about any command - init Initialize a newly installed garm - organization Manage organizations - pool List pools - profile Add, delete or update profiles - provider Interacts with the providers API resource. - repository Manage repositories - runner List runners in a pool - version Print version and exit - - Flags: - --debug Enable debug on all API calls - -h, --help help for garm-cli - - Use "garm-cli [command] --help" for more information about a command. - - ``` diff --git a/doc/webhooks.md b/doc/webhooks.md new file mode 100644 index 00000000..d2690bfb --- /dev/null +++ b/doc/webhooks.md @@ -0,0 +1,56 @@ +# Webhooks + +Garm is designed to auto-scale github runners. To achieve this, ```garm``` relies on [GitHub Webhooks](https://docs.github.com/en/developers/webhooks-and-events/webhooks/about-webhooks). Webhooks allow ```garm``` to react to workflow events from your repository, organization or enterprise. + +In your repository or organization, navigate to ```Settings --> Webhooks```: + +![webhooks](images/webhooks.png) + +And click on ```Add webhook```. + +In the ```Payload URL``` field, enter the URL to the ```garm``` webhook endpoint. The ```garm``` API endpoint for webhooks is: + + ```txt + POST /webhooks + ``` + +If ```garm``` is running on a server under the domain ```garm.example.com```, then that field should be set to ```https://garm.example.com/webhooks```. + +In the webhook configuration page under ```Content type``` you will need to select ```application/json```, set the proper webhook URL and, really important, **make sure you configure a webhook secret**. Garm will authenticate the payloads to make sure they are coming from GitHub. + +The webhook secret must be secure. Use something like this to generate one: + + ```bash + gabriel@rossak:~$ function generate_secret () { + tr -dc 'a-zA-Z0-9!@#$%^&*()_+?><~\`;' < /dev/urandom | head -c 64; + echo '' + } + + gabriel@rossak:~$ generate_secret + 9Q*nsr*S54g0imK64(!2$Ns6C!~VsH(p)cFj+AMLug%LM!R%FOQ + ``` + +Make a note of that secret, as you'll need it later when you define the repo/org/enterprise in ```GARM```. + +![webhook](images/input_url.png) + +While you can use `http` for your webhook, I highly recommend you set up a proper x509 certificate for your GARM server and use `https` instead. If you choose `https`, GitHub will present you with an aditional option to configure the SSL certificate verification. + +![ssl](images/tls_config.png) + +If you're testing and want to use a self signed certificate, you can disable SSL verification or just use `http`, but for production you should use `https` with a proper certificate and SSL verification set to `enabled`. + +It's fairly trivial to set up a proper x509 certificate for your GARM server. You can use [Let's Encrypt](https://letsencrypt.org/) to get a free certificate. + + +Next, you can choose which events GitHub should send to ```garm``` via webhooks. Click on ```Let me select individual events```. + +![events](images/select_events.png) + +Now select ```Workflow jobs``` (should be at the bottom). You can send everything if you want, but any events ```garm``` doesn't care about will simply be ignored. + +![workflow](images/jobs.png) + +Finally, click on ```Add webhook``` and you're done. + +GitHub will send a test webhook to your endpoint. If all is well, you should see a green checkmark next to your webhook. \ No newline at end of file diff --git a/doc/webhooks_and_callbacks.md b/doc/webhooks_and_callbacks.md deleted file mode 100644 index dfe1b3a1..00000000 --- a/doc/webhooks_and_callbacks.md +++ /dev/null @@ -1,94 +0,0 @@ -# Webhooks - -Garm is designed to auto-scale github runners based on a few simple rules: - -* A minimum idle runner count can be set for a pool. Garm will attempt to maintain that minimum of idle runners, ready to be used by your workflows. -* A maximum number of runners for a pool. This is a hard limit of runners a pool will create, regardless of minimum idle runners. -* When a runner is scheduled by github, ```garm``` will automatically spin up a new runner to replace it, obeying the maximum hard limit defined. - -To achieve this, ```garm``` relies on [GitHub Webhooks](https://docs.github.com/en/developers/webhooks-and-events/webhooks/about-webhooks). Webhooks allow ```garm``` to react to workflow events from your repository or organization. - -In your repository or organization, navigate to ```Settings --> Webhooks```. In the ```Payload URL``` field, enter the URL to the ```garm``` webhook endpoint. The ```garm``` API endpoint for webhooks is: - - ```txt - POST /webhooks - ``` - -If ```garm``` is running on a server under the domain ```garm.example.com```, then that field should be set to ```https://garm.example.com/webhooks```. - -In the webhook configuration page under ```Content type``` you will need to select ```application/json```, set the proper webhook URL and, really important, **make sure you configure a webhook secret**. Garm will authenticate the payloads to make sure they are coming from GitHub. - -The webhook secret must be secure. Use something like this to generate one: - - ```bash - gabriel@rossak:~$ function generate_secret () { - tr -dc 'a-zA-Z0-9!@#$%^&*()_+?><~\`;' < /dev/urandom | head -c 64; - echo '' - } - - gabriel@rossak:~$ generate_secret - 9Q*nsr*S54g0imK64(!2$Ns6C!~VsH(p)cFj+AMLug%LM!R%FOQ - ``` - -Next, you can choose which events GitHub should send to ```garm``` via webhooks. Click on ```Let me select individual events``` and select ```Workflow jobs``` (should be at the bottom). You can send everything if you want, but any events ```garm``` doesn't care about will simply be ignored. - -## The callback_url option - -Your runners will call back home with status updates as they install. Once they are set up, they will also send the GitHub agent ID they were allocated. You will need to configure the ```callback_url``` option in the ```garm``` server config. This URL needs to point to the following API endpoint: - - ```txt - POST /api/v1/callbacks/status - ``` - -Example of a runner sending status updates: - - ```bash - garm-cli runner show garm-f5227755-129d-4e2d-b306-377a8f3a5dfe - +-----------------+--------------------------------------------------------------------------------------------------------------------------------------------------+ - | FIELD | VALUE | - +-----------------+--------------------------------------------------------------------------------------------------------------------------------------------------+ - | ID | 1afb407b-e9f7-4d75-a410-fc4a8c2dbe6c | - | Provider ID | garm-f5227755-129d-4e2d-b306-377a8f3a5dfe | - | Name | garm-f5227755-129d-4e2d-b306-377a8f3a5dfe | - | OS Type | linux | - | OS Architecture | amd64 | - | OS Name | ubuntu | - | OS Version | focal | - | Status | running | - | Runner Status | idle | - | Pool ID | 98f438b9-5549-4eaf-9bb7-1781533a455d | - | Status Updates | 2022-05-05T11:32:41: downloading tools from https://github.com/actions/runner/releases/download/v2.290.1/actions-runner-linux-x64-2.290.1.tar.gz | - | | 2022-05-05T11:32:43: extracting runner | - | | 2022-05-05T11:32:47: installing dependencies | - | | 2022-05-05T11:32:55: configuring runner | - | | 2022-05-05T11:32:59: installing runner service | - | | 2022-05-05T11:33:00: starting service | - | | 2022-05-05T11:33:00: runner successfully installed | - +-----------------+--------------------------------------------------------------------------------------------------------------------------------------------------+ - ``` - -This URL must be set and must be accessible by the instance. If you wish to restrict access to it, a reverse proxy can be configured to accept requests only from networks in which the runners ```garm``` manages will be spun up. This URL doesn't need to be globally accessible, it just needs to be accessible by the instances. - -For example, in a scenario where you expose the API endpoint directly, this setting could look like the following: - - ```toml - callback_url = "https://garm.example.com/api/v1/callbacks/status" - ``` - -Authentication is done using a short-lived JWT token, that gets generated for a particular instance that we are spinning up. That JWT token grants access to the instance to only update it's own status and to fetch metadata for itself. No other API endpoints will work with that JWT token. The validity of the token is equal to the pool bootstrap timeout value (default 20 minutes) plus the garm polling interval (5 minutes). - -There is a sample ```nginx``` config [in the testdata folder](/testdata/nginx-server.conf). Feel free to customize it whichever way you see fit. - -## The metadata_url option - -The metadata URL is the base URL for any information an instance may need to fetch in order to finish setting itself up. As this URL may be placed behind a reverse proxy, you'll need to configure it in the ```garm``` config file. Ultimately this URL will need to point to the following ```garm``` API endpoint: - - ```bash - GET /api/v1/metadata - ``` - -This URL needs to be accessible only by the instances ```garm``` sets up. This URL will not be used by anyone else. To configure it in ```garm``` add the following line in the ```[default]``` section of your ```garm``` config: - - ```toml - metadata_url = "https://garm.example.com/api/v1/metadata" - ``` diff --git a/go.mod b/go.mod index 3cad3c06..150c2b3b 100644 --- a/go.mod +++ b/go.mod @@ -4,10 +4,10 @@ go 1.20 require ( github.com/BurntSushi/toml v1.2.1 + github.com/cloudbase/garm-provider-common v0.0.0-20230724114054-7aa0a3dfbce0 github.com/go-openapi/errors v0.20.4 github.com/go-openapi/runtime v0.26.0 github.com/go-openapi/strfmt v0.21.7 - github.com/go-resty/resty/v2 v2.7.0 github.com/golang-jwt/jwt v3.2.2+incompatible github.com/google/go-github/v53 v53.2.0 github.com/google/uuid v1.3.0 @@ -19,20 +19,16 @@ require ( github.com/juju/retry v1.0.0 github.com/lxc/lxd v0.0.0-20230325180147-8d608287b0ce github.com/manifoldco/promptui v0.9.0 - github.com/mattn/go-isatty v0.0.18 github.com/nbutton23/zxcvbn-go v0.0.0-20210217022336-fa2cb2858354 github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.14.0 github.com/spf13/cobra v1.6.1 github.com/stretchr/testify v1.8.2 - github.com/teris-io/shortid v0.0.0-20220617161101-71ec9f2aa569 golang.org/x/crypto v0.7.0 golang.org/x/oauth2 v0.8.0 golang.org/x/sync v0.1.0 - golang.org/x/sys v0.8.0 gopkg.in/DATA-DOG/go-sqlmock.v1 v1.3.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 - gopkg.in/yaml.v3 v3.0.1 gorm.io/datatypes v1.1.1 gorm.io/driver/mysql v1.4.7 gorm.io/driver/sqlite v1.4.4 @@ -76,6 +72,7 @@ require ( github.com/kr/fs v0.1.0 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/mailru/easyjson v0.7.7 // indirect + github.com/mattn/go-isatty v0.0.19 // indirect github.com/mattn/go-runewidth v0.0.14 // indirect github.com/mattn/go-sqlite3 v1.14.16 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect @@ -95,10 +92,12 @@ require ( github.com/sirupsen/logrus v1.9.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/stretchr/objx v0.5.0 // indirect + github.com/teris-io/shortid v0.0.0-20220617161101-71ec9f2aa569 // indirect go.mongodb.org/mongo-driver v1.11.3 // indirect go.opentelemetry.io/otel v1.14.0 // indirect go.opentelemetry.io/otel/trace v1.14.0 // indirect golang.org/x/net v0.10.0 // indirect + golang.org/x/sys v0.8.0 // indirect golang.org/x/term v0.8.0 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/protobuf v1.30.0 // indirect @@ -106,4 +105,5 @@ require ( gopkg.in/httprequest.v1 v1.2.1 // indirect gopkg.in/macaroon.v2 v2.1.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index a17e54c8..eadba3dd 100644 --- a/go.sum +++ b/go.sum @@ -25,6 +25,8 @@ github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMn github.com/chzyer/test v1.0.0 h1:p3BQDXSxOhOG0P9z6/hGnII4LGiEPOYBhs8asl/fC04= github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudbase/garm-provider-common v0.0.0-20230724114054-7aa0a3dfbce0 h1:5ScMXea/ZIcUbw1aXAgN8xTqSG84AOf5Maf5hBC82wQ= +github.com/cloudbase/garm-provider-common v0.0.0-20230724114054-7aa0a3dfbce0/go.mod h1:RKzgL0MXkNeGfloQpE2swz/y4LWJr5+2Wd45bSXPB0k= github.com/cloudflare/circl v1.1.0/go.mod h1:prBCrKB9DV4poKZY1l9zBXg2QJY7mvgRvtMxxK7fi4I= github.com/cloudflare/circl v1.3.3 h1:fE/Qz0QdIGqeWfnwq0RE0R7MI51s0M2E4Ga9kq5AEMs= github.com/cloudflare/circl v1.3.3/go.mod h1:5XYMA4rFBvNIrhs50XuiBJ15vF2pZn4nnUKZrLbUZFA= @@ -90,8 +92,6 @@ github.com/go-openapi/swag v0.22.4 h1:QLMzNJnMGPRNDCbySlcj1x01tzU8/9LTTL9hZZZogB github.com/go-openapi/swag v0.22.4/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= github.com/go-openapi/validate v0.22.1 h1:G+c2ub6q47kfX1sOBLwIQwzBVt8qmOAARyo/9Fqs9NU= github.com/go-openapi/validate v0.22.1/go.mod h1:rjnrwK57VJ7A8xqfpAOEKRH8yQSGUriMu5/zuPSQ1hg= -github.com/go-resty/resty/v2 v2.7.0 h1:me+K9p3uhSmXtrBZ4k9jcEAfJmuC8IivWHwaLZwPrFY= -github.com/go-resty/resty/v2 v2.7.0/go.mod h1:9PWDzw47qPphMRFfhsyk0NnSgvluHcljSMVIq3w7q0I= github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc= github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= @@ -231,8 +231,8 @@ github.com/manifoldco/promptui v0.9.0 h1:3V4HzJk1TtXW1MTZMP7mdlwbBpIinw3HztaIlYt github.com/manifoldco/promptui v0.9.0/go.mod h1:ka04sppxSGFAtxX0qhlYQjISsg9mR4GWtQEhdbn6Pgg= github.com/markbates/oncer v0.0.0-20181203154359-bf2de49a0be2/go.mod h1:Ld9puTsIW75CHf65OeIOkyKbteujpZVXDpWK6YGZbxE= github.com/markbates/safe v1.0.1/go.mod h1:nAqgmRi7cY2nqMc92/bSEeQA+R4OheNU2T1kNSCBdG0= -github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98= -github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU= github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= @@ -367,7 +367,6 @@ golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20200505041828-1ed23360d12c/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= -golang.org/x/net v0.0.0-20211029224645-99673261e6eb/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= diff --git a/params/params.go b/params/params.go index bb84b8d9..83aa2abc 100644 --- a/params/params.go +++ b/params/params.go @@ -18,7 +18,8 @@ import ( "encoding/json" "time" - "github.com/cloudbase/garm/runner/providers/common" + commonParams "github.com/cloudbase/garm-provider-common/params" + "github.com/cloudbase/garm/util/appdefaults" "github.com/google/go-github/v53/github" @@ -27,13 +28,11 @@ import ( type ( PoolType string - AddressType string EventType string EventLevel string - OSType string - OSArch string ProviderType string JobStatus string + RunnerStatus string ) const ( @@ -55,11 +54,6 @@ const ( EnterprisePool PoolType = "enterprise" ) -const ( - PublicAddress AddressType = "public" - PrivateAddress AddressType = "private" -) - const ( StatusEvent EventType = "status" FetchTokenEvent EventType = "fetchToken" @@ -72,23 +66,14 @@ const ( ) const ( - Windows OSType = "windows" - Linux OSType = "linux" - Unknown OSType = "unknown" -) - -const ( - Amd64 OSArch = "amd64" - I386 OSArch = "i386" - Arm64 OSArch = "arm64" - Arm OSArch = "arm" + RunnerIdle RunnerStatus = "idle" + RunnerPending RunnerStatus = "pending" + RunnerTerminated RunnerStatus = "terminated" + RunnerInstalling RunnerStatus = "installing" + RunnerFailed RunnerStatus = "failed" + RunnerActive RunnerStatus = "active" ) -type Address struct { - Address string `json:"address"` - Type AddressType `json:"type"` -} - type StatusMessage struct { CreatedAt time.Time `json:"created_at"` Message string `json:"message"` @@ -116,7 +101,7 @@ type Instance struct { // OSType is the operating system type. For now, only Linux and // Windows are supported. - OSType OSType `json:"os_type,omitempty"` + OSType commonParams.OSType `json:"os_type,omitempty"` // OSName is the name of the OS. Eg: ubuntu, centos, etc. OSName string `json:"os_name,omitempty"` @@ -125,17 +110,17 @@ type Instance struct { OSVersion string `json:"os_version,omitempty"` // OSArch is the operating system architecture. - OSArch OSArch `json:"os_arch,omitempty"` + OSArch commonParams.OSArch `json:"os_arch,omitempty"` // Addresses is a list of IP addresses the provider reports // for this instance. - Addresses []Address `json:"addresses,omitempty"` + Addresses []commonParams.Address `json:"addresses,omitempty"` // Status is the status of the instance inside the provider (eg: running, stopped, etc) - Status common.InstanceStatus `json:"status,omitempty"` + Status commonParams.InstanceStatus `json:"status,omitempty"` // RunnerStatus is the github runner status as it appears on GitHub. - RunnerStatus common.RunnerStatus `json:"runner_status,omitempty"` + RunnerStatus RunnerStatus `json:"runner_status,omitempty"` // PoolID is the ID of the garm pool to which a runner belongs. PoolID string `json:"pool_id,omitempty"` @@ -208,10 +193,10 @@ type BootstrapInstance struct { CACertBundle []byte `json:"ca-cert-bundle"` // OSArch is the target OS CPU architecture of the runner. - OSArch OSArch `json:"arch"` + OSArch commonParams.OSArch `json:"arch"` // OSType is the target OS platform of the runner (windows, linux). - OSType OSType `json:"os_type"` + OSType commonParams.OSType `json:"os_type"` // Flavor is the platform specific abstraction that defines what resources will be allocated // to the runner (CPU, RAM, disk space, etc). This field is meaningful to the provider which @@ -245,24 +230,24 @@ type Tag struct { type Pool struct { RunnerPrefix - ID string `json:"id"` - ProviderName string `json:"provider_name"` - MaxRunners uint `json:"max_runners"` - MinIdleRunners uint `json:"min_idle_runners"` - Image string `json:"image"` - Flavor string `json:"flavor"` - OSType OSType `json:"os_type"` - OSArch OSArch `json:"os_arch"` - Tags []Tag `json:"tags"` - Enabled bool `json:"enabled"` - Instances []Instance `json:"instances"` - RepoID string `json:"repo_id,omitempty"` - RepoName string `json:"repo_name,omitempty"` - OrgID string `json:"org_id,omitempty"` - OrgName string `json:"org_name,omitempty"` - EnterpriseID string `json:"enterprise_id,omitempty"` - EnterpriseName string `json:"enterprise_name,omitempty"` - RunnerBootstrapTimeout uint `json:"runner_bootstrap_timeout"` + ID string `json:"id"` + ProviderName string `json:"provider_name"` + MaxRunners uint `json:"max_runners"` + MinIdleRunners uint `json:"min_idle_runners"` + Image string `json:"image"` + Flavor string `json:"flavor"` + OSType commonParams.OSType `json:"os_type"` + OSArch commonParams.OSArch `json:"os_arch"` + Tags []Tag `json:"tags"` + Enabled bool `json:"enabled"` + Instances []Instance `json:"instances"` + RepoID string `json:"repo_id,omitempty"` + RepoName string `json:"repo_name,omitempty"` + OrgID string `json:"org_id,omitempty"` + OrgName string `json:"org_name,omitempty"` + EnterpriseID string `json:"enterprise_id,omitempty"` + EnterpriseName string `json:"enterprise_name,omitempty"` + RunnerBootstrapTimeout uint `json:"runner_bootstrap_timeout"` // ExtraSpecs is an opaque raw json that gets sent to the provider // as part of the bootstrap params for instances. It can contain // any kind of data needed by providers. The contents of this field means @@ -350,6 +335,9 @@ func (o Organization) GetID() string { return o.ID } +// used by swagger client generated code +type Organizations []Organization + type Enterprise struct { ID string `json:"id"` Name string `json:"name"` @@ -368,6 +356,9 @@ func (e Enterprise) GetID() string { return e.ID } +// used by swagger client generated code +type Enterprises []Enterprise + // Users holds information about a particular user type User struct { ID string `json:"id"` @@ -401,12 +392,18 @@ type GithubCredentials struct { CABundle []byte `json:"ca_bundle,omitempty"` } +// used by swagger client generated code +type Credentials []GithubCredentials + type Provider struct { Name string `json:"name"` ProviderType ProviderType `json:"type"` Description string `json:"description"` } +// used by swagger client generated code +type Providers []Provider + type UpdatePoolStateParams struct { WebhookSecret string InternalConfig *Internal @@ -482,3 +479,6 @@ type Job struct { CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` } + +// used by swagger client generated code +type Jobs []Job diff --git a/params/requests.go b/params/requests.go index e2dd1c9d..8b333662 100644 --- a/params/requests.go +++ b/params/requests.go @@ -18,16 +18,17 @@ import ( "encoding/json" "fmt" - "github.com/cloudbase/garm/errors" - "github.com/cloudbase/garm/runner/providers/common" + commonParams "github.com/cloudbase/garm-provider-common/params" + + "github.com/cloudbase/garm-provider-common/errors" ) const DefaultRunnerPrefix = "garm" type InstanceRequest struct { - Name string `json:"name"` - OSType OSType `json:"os_type"` - OSVersion string `json:"os_version"` + Name string `json:"name"` + OSType commonParams.OSType `json:"os_type"` + OSVersion string `json:"os_version"` } type CreateRepoParams struct { @@ -108,16 +109,16 @@ type NewUserParams struct { type UpdatePoolParams struct { RunnerPrefix - Tags []string `json:"tags,omitempty"` - Enabled *bool `json:"enabled,omitempty"` - MaxRunners *uint `json:"max_runners,omitempty"` - MinIdleRunners *uint `json:"min_idle_runners,omitempty"` - RunnerBootstrapTimeout *uint `json:"runner_bootstrap_timeout,omitempty"` - Image string `json:"image"` - Flavor string `json:"flavor"` - OSType OSType `json:"os_type"` - OSArch OSArch `json:"os_arch"` - ExtraSpecs json.RawMessage `json:"extra_specs,omitempty"` + Tags []string `json:"tags,omitempty"` + Enabled *bool `json:"enabled,omitempty"` + MaxRunners *uint `json:"max_runners,omitempty"` + MinIdleRunners *uint `json:"min_idle_runners,omitempty"` + RunnerBootstrapTimeout *uint `json:"runner_bootstrap_timeout,omitempty"` + Image string `json:"image"` + Flavor string `json:"flavor"` + OSType commonParams.OSType `json:"os_type"` + OSArch commonParams.OSArch `json:"os_arch"` + ExtraSpecs json.RawMessage `json:"extra_specs,omitempty"` // GithubRunnerGroup is the github runner group in which the runners of this // pool will be added to. // The runner group must be created by someone with access to the enterprise. @@ -126,10 +127,10 @@ type UpdatePoolParams struct { type CreateInstanceParams struct { Name string - OSType OSType - OSArch OSArch - Status common.InstanceStatus - RunnerStatus common.RunnerStatus + OSType commonParams.OSType + OSArch commonParams.OSArch + Status commonParams.InstanceStatus + RunnerStatus RunnerStatus CallbackURL string MetadataURL string // GithubRunnerGroup is the github runner group to which the runner belongs. @@ -142,17 +143,17 @@ type CreateInstanceParams struct { type CreatePoolParams struct { RunnerPrefix - ProviderName string `json:"provider_name"` - MaxRunners uint `json:"max_runners"` - MinIdleRunners uint `json:"min_idle_runners"` - Image string `json:"image"` - Flavor string `json:"flavor"` - OSType OSType `json:"os_type"` - OSArch OSArch `json:"os_arch"` - Tags []string `json:"tags"` - Enabled bool `json:"enabled"` - RunnerBootstrapTimeout uint `json:"runner_bootstrap_timeout"` - ExtraSpecs json.RawMessage `json:"extra_specs,omitempty"` + ProviderName string `json:"provider_name"` + MaxRunners uint `json:"max_runners"` + MinIdleRunners uint `json:"min_idle_runners"` + Image string `json:"image"` + Flavor string `json:"flavor"` + OSType commonParams.OSType `json:"os_type"` + OSArch commonParams.OSArch `json:"os_arch"` + Tags []string `json:"tags"` + Enabled bool `json:"enabled"` + RunnerBootstrapTimeout uint `json:"runner_bootstrap_timeout"` + ExtraSpecs json.RawMessage `json:"extra_specs,omitempty"` // GithubRunnerGroup is the github runner group in which the runners of this // pool will be added to. // The runner group must be created by someone with access to the enterprise. @@ -195,14 +196,14 @@ type UpdateInstanceParams struct { OSVersion string `json:"os_version,omitempty"` // Addresses is a list of IP addresses the provider reports // for this instance. - Addresses []Address `json:"addresses,omitempty"` + Addresses []commonParams.Address `json:"addresses,omitempty"` // Status is the status of the instance inside the provider (eg: running, stopped, etc) - Status common.InstanceStatus `json:"status,omitempty"` - RunnerStatus common.RunnerStatus `json:"runner_status,omitempty"` - ProviderFault []byte `json:"provider_fault,omitempty"` - AgentID int64 `json:"-"` - CreateAttempt int `json:"-"` - TokenFetched *bool `json:"-"` + Status commonParams.InstanceStatus `json:"status,omitempty"` + RunnerStatus RunnerStatus `json:"runner_status,omitempty"` + ProviderFault []byte `json:"provider_fault,omitempty"` + AgentID int64 `json:"-"` + CreateAttempt int `json:"-"` + TokenFetched *bool `json:"-"` } type UpdateUserParams struct { @@ -233,7 +234,7 @@ type UpdateEntityParams struct { } type InstanceUpdateMessage struct { - Status common.RunnerStatus `json:"status"` - Message string `json:"message"` - AgentID *int64 `json:"agent_id"` + Status RunnerStatus `json:"status"` + Message string `json:"message"` + AgentID *int64 `json:"agent_id"` } diff --git a/runner/common/mocks/Provider.go b/runner/common/mocks/Provider.go index 7f9d801f..e5157e0f 100644 --- a/runner/common/mocks/Provider.go +++ b/runner/common/mocks/Provider.go @@ -5,8 +5,10 @@ package mocks import ( context "context" - params "github.com/cloudbase/garm/params" + garm_provider_commonparams "github.com/cloudbase/garm-provider-common/params" mock "github.com/stretchr/testify/mock" + + params "github.com/cloudbase/garm/params" ) // Provider is an autogenerated mock type for the Provider type @@ -29,21 +31,21 @@ func (_m *Provider) AsParams() params.Provider { } // CreateInstance provides a mock function with given fields: ctx, bootstrapParams -func (_m *Provider) CreateInstance(ctx context.Context, bootstrapParams params.BootstrapInstance) (params.Instance, error) { +func (_m *Provider) CreateInstance(ctx context.Context, bootstrapParams garm_provider_commonparams.BootstrapInstance) (garm_provider_commonparams.ProviderInstance, error) { ret := _m.Called(ctx, bootstrapParams) - var r0 params.Instance + var r0 garm_provider_commonparams.ProviderInstance var r1 error - if rf, ok := ret.Get(0).(func(context.Context, params.BootstrapInstance) (params.Instance, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, garm_provider_commonparams.BootstrapInstance) (garm_provider_commonparams.ProviderInstance, error)); ok { return rf(ctx, bootstrapParams) } - if rf, ok := ret.Get(0).(func(context.Context, params.BootstrapInstance) params.Instance); ok { + if rf, ok := ret.Get(0).(func(context.Context, garm_provider_commonparams.BootstrapInstance) garm_provider_commonparams.ProviderInstance); ok { r0 = rf(ctx, bootstrapParams) } else { - r0 = ret.Get(0).(params.Instance) + r0 = ret.Get(0).(garm_provider_commonparams.ProviderInstance) } - if rf, ok := ret.Get(1).(func(context.Context, params.BootstrapInstance) error); ok { + if rf, ok := ret.Get(1).(func(context.Context, garm_provider_commonparams.BootstrapInstance) error); ok { r1 = rf(ctx, bootstrapParams) } else { r1 = ret.Error(1) @@ -67,18 +69,18 @@ func (_m *Provider) DeleteInstance(ctx context.Context, instance string) error { } // GetInstance provides a mock function with given fields: ctx, instance -func (_m *Provider) GetInstance(ctx context.Context, instance string) (params.Instance, error) { +func (_m *Provider) GetInstance(ctx context.Context, instance string) (garm_provider_commonparams.ProviderInstance, error) { ret := _m.Called(ctx, instance) - var r0 params.Instance + var r0 garm_provider_commonparams.ProviderInstance var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string) (params.Instance, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, string) (garm_provider_commonparams.ProviderInstance, error)); ok { return rf(ctx, instance) } - if rf, ok := ret.Get(0).(func(context.Context, string) params.Instance); ok { + if rf, ok := ret.Get(0).(func(context.Context, string) garm_provider_commonparams.ProviderInstance); ok { r0 = rf(ctx, instance) } else { - r0 = ret.Get(0).(params.Instance) + r0 = ret.Get(0).(garm_provider_commonparams.ProviderInstance) } if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { @@ -91,19 +93,19 @@ func (_m *Provider) GetInstance(ctx context.Context, instance string) (params.In } // ListInstances provides a mock function with given fields: ctx, poolID -func (_m *Provider) ListInstances(ctx context.Context, poolID string) ([]params.Instance, error) { +func (_m *Provider) ListInstances(ctx context.Context, poolID string) ([]garm_provider_commonparams.ProviderInstance, error) { ret := _m.Called(ctx, poolID) - var r0 []params.Instance + var r0 []garm_provider_commonparams.ProviderInstance var r1 error - if rf, ok := ret.Get(0).(func(context.Context, string) ([]params.Instance, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, string) ([]garm_provider_commonparams.ProviderInstance, error)); ok { return rf(ctx, poolID) } - if rf, ok := ret.Get(0).(func(context.Context, string) []params.Instance); ok { + if rf, ok := ret.Get(0).(func(context.Context, string) []garm_provider_commonparams.ProviderInstance); ok { r0 = rf(ctx, poolID) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]params.Instance) + r0 = ret.Get(0).([]garm_provider_commonparams.ProviderInstance) } } diff --git a/runner/common/provider.go b/runner/common/provider.go index 2def7385..1cdb7fbe 100644 --- a/runner/common/provider.go +++ b/runner/common/provider.go @@ -17,19 +17,20 @@ package common import ( "context" + commonParams "github.com/cloudbase/garm-provider-common/params" "github.com/cloudbase/garm/params" ) //go:generate mockery --all type Provider interface { // CreateInstance creates a new compute instance in the provider. - CreateInstance(ctx context.Context, bootstrapParams params.BootstrapInstance) (params.Instance, error) + CreateInstance(ctx context.Context, bootstrapParams commonParams.BootstrapInstance) (commonParams.ProviderInstance, error) // Delete instance will delete the instance in a provider. DeleteInstance(ctx context.Context, instance string) error // GetInstance will return details about one instance. - GetInstance(ctx context.Context, instance string) (params.Instance, error) + GetInstance(ctx context.Context, instance string) (commonParams.ProviderInstance, error) // ListInstances will list all instances for a provider. - ListInstances(ctx context.Context, poolID string) ([]params.Instance, error) + ListInstances(ctx context.Context, poolID string) ([]commonParams.ProviderInstance, error) // RemoveAllInstances will remove all instances created by this provider. RemoveAllInstances(ctx context.Context) error // Stop shuts down the instance. diff --git a/runner/enterprises.go b/runner/enterprises.go index 82993591..b86a4284 100644 --- a/runner/enterprises.go +++ b/runner/enterprises.go @@ -6,8 +6,8 @@ import ( "log" "strings" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/auth" - runnerErrors "github.com/cloudbase/garm/errors" "github.com/cloudbase/garm/params" "github.com/cloudbase/garm/runner/common" "github.com/cloudbase/garm/util/appdefaults" diff --git a/runner/enterprises_test.go b/runner/enterprises_test.go index 8541a1a7..809577a7 100644 --- a/runner/enterprises_test.go +++ b/runner/enterprises_test.go @@ -19,11 +19,11 @@ import ( "fmt" "testing" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/auth" "github.com/cloudbase/garm/config" "github.com/cloudbase/garm/database" dbCommon "github.com/cloudbase/garm/database/common" - runnerErrors "github.com/cloudbase/garm/errors" garmTesting "github.com/cloudbase/garm/internal/testing" "github.com/cloudbase/garm/params" "github.com/cloudbase/garm/runner/common" diff --git a/runner/organizations.go b/runner/organizations.go index 37bd4348..61ebcc6a 100644 --- a/runner/organizations.go +++ b/runner/organizations.go @@ -20,8 +20,8 @@ import ( "log" "strings" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/auth" - runnerErrors "github.com/cloudbase/garm/errors" "github.com/cloudbase/garm/params" "github.com/cloudbase/garm/runner/common" "github.com/cloudbase/garm/util/appdefaults" diff --git a/runner/organizations_test.go b/runner/organizations_test.go index 073ff6fb..f6c1e170 100644 --- a/runner/organizations_test.go +++ b/runner/organizations_test.go @@ -19,11 +19,11 @@ import ( "fmt" "testing" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/auth" "github.com/cloudbase/garm/config" "github.com/cloudbase/garm/database" dbCommon "github.com/cloudbase/garm/database/common" - runnerErrors "github.com/cloudbase/garm/errors" garmTesting "github.com/cloudbase/garm/internal/testing" "github.com/cloudbase/garm/params" "github.com/cloudbase/garm/runner/common" diff --git a/runner/pool/enterprise.go b/runner/pool/enterprise.go index d381a025..025c3415 100644 --- a/runner/pool/enterprise.go +++ b/runner/pool/enterprise.go @@ -7,8 +7,8 @@ import ( "strings" "sync" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" dbCommon "github.com/cloudbase/garm/database/common" - runnerErrors "github.com/cloudbase/garm/errors" "github.com/cloudbase/garm/params" "github.com/cloudbase/garm/runner/common" "github.com/cloudbase/garm/util" diff --git a/runner/pool/organization.go b/runner/pool/organization.go index af650abc..a8a6ed9d 100644 --- a/runner/pool/organization.go +++ b/runner/pool/organization.go @@ -21,8 +21,8 @@ import ( "strings" "sync" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" dbCommon "github.com/cloudbase/garm/database/common" - runnerErrors "github.com/cloudbase/garm/errors" "github.com/cloudbase/garm/params" "github.com/cloudbase/garm/runner/common" "github.com/cloudbase/garm/util" diff --git a/runner/pool/pool.go b/runner/pool/pool.go index ce98367e..a2516605 100644 --- a/runner/pool/pool.go +++ b/runner/pool/pool.go @@ -25,13 +25,14 @@ import ( "sync" "time" + commonParams "github.com/cloudbase/garm-provider-common/params" + + runnerErrors "github.com/cloudbase/garm-provider-common/errors" + "github.com/cloudbase/garm-provider-common/util" "github.com/cloudbase/garm/auth" dbCommon "github.com/cloudbase/garm/database/common" - runnerErrors "github.com/cloudbase/garm/errors" "github.com/cloudbase/garm/params" "github.com/cloudbase/garm/runner/common" - providerCommon "github.com/cloudbase/garm/runner/providers/common" - "github.com/cloudbase/garm/util" "github.com/google/go-github/v53/github" "github.com/google/uuid" @@ -176,7 +177,7 @@ func (r *basePoolManager) HandleWorkflowJob(job params.WorkflowJob) error { } // update instance workload state. - if _, err := r.setInstanceRunnerStatus(jobParams.RunnerName, providerCommon.RunnerTerminated); err != nil { + if _, err := r.setInstanceRunnerStatus(jobParams.RunnerName, params.RunnerTerminated); err != nil { if errors.Is(err, runnerErrors.ErrNotFound) { return nil } @@ -184,7 +185,7 @@ func (r *basePoolManager) HandleWorkflowJob(job params.WorkflowJob) error { return errors.Wrap(err, "updating runner") } r.log("marking instance %s as pending_delete", util.SanitizeLogEntry(jobParams.RunnerName)) - if _, err := r.setInstanceStatus(jobParams.RunnerName, providerCommon.InstancePendingDelete, nil); err != nil { + if _, err := r.setInstanceStatus(jobParams.RunnerName, commonParams.InstancePendingDelete, nil); err != nil { if errors.Is(err, runnerErrors.ErrNotFound) { return nil } @@ -206,7 +207,7 @@ func (r *basePoolManager) HandleWorkflowJob(job params.WorkflowJob) error { } // update instance workload state. - instance, err := r.setInstanceRunnerStatus(jobParams.RunnerName, providerCommon.RunnerActive) + instance, err := r.setInstanceRunnerStatus(jobParams.RunnerName, params.RunnerActive) if err != nil { if errors.Is(err, runnerErrors.ErrNotFound) { return nil @@ -370,9 +371,9 @@ func (r *basePoolManager) cleanupOrphanedProviderRunners(runners []*github.Runne } defer r.keyMux.Unlock(instance.Name, false) - switch providerCommon.InstanceStatus(instance.Status) { - case providerCommon.InstancePendingCreate, - providerCommon.InstancePendingDelete: + switch commonParams.InstanceStatus(instance.Status) { + case commonParams.InstancePendingCreate, + commonParams.InstancePendingDelete: // this instance is in the process of being created or is awaiting deletion. // Instances in pending_create did not get a chance to register themselves in, // github so we let them be for now. @@ -380,7 +381,7 @@ func (r *basePoolManager) cleanupOrphanedProviderRunners(runners []*github.Runne } switch instance.RunnerStatus { - case providerCommon.RunnerPending, providerCommon.RunnerInstalling: + case params.RunnerPending, params.RunnerInstalling: // runner is still installing. We give it a chance to finish. r.log("runner %s is still installing, give it a chance to finish", instance.Name) continue @@ -394,7 +395,7 @@ func (r *basePoolManager) cleanupOrphanedProviderRunners(runners []*github.Runne if ok := runnerNames[instance.Name]; !ok { // Set pending_delete on DB field. Allow consolidate() to remove it. - if _, err := r.setInstanceStatus(instance.Name, providerCommon.InstancePendingDelete, nil); err != nil { + if _, err := r.setInstanceStatus(instance.Name, commonParams.InstancePendingDelete, nil); err != nil { r.log("failed to update runner %s status: %s", instance.Name, err) return errors.Wrap(err, "updating runner") } @@ -455,7 +456,7 @@ func (r *basePoolManager) reapTimedOutRunners(runners []*github.Runner) error { // even though, technically the runner is online and fully functional. This is why we check here for // both the runner status as reported by GitHub and the runner status as reported by the provider. // If the runner is "offline" and marked as "failed", it should be safe to reap it. - if runner, ok := runnersByName[instance.Name]; !ok || (runner.GetStatus() == "offline" && instance.RunnerStatus == providerCommon.RunnerFailed) { + if runner, ok := runnersByName[instance.Name]; !ok || (runner.GetStatus() == "offline" && instance.RunnerStatus == params.RunnerFailed) { r.log("reaping timed-out/failed runner %s", instance.Name) if err := r.ForceDeleteRunner(instance); err != nil { r.log("failed to update runner %s status: %s", instance.Name, err) @@ -466,13 +467,13 @@ func (r *basePoolManager) reapTimedOutRunners(runners []*github.Runner) error { return nil } -func instanceInList(instanceName string, instances []params.Instance) (params.Instance, bool) { +func instanceInList(instanceName string, instances []commonParams.ProviderInstance) (commonParams.ProviderInstance, bool) { for _, val := range instances { if val.Name == instanceName { return val, true } } - return params.Instance{}, false + return commonParams.ProviderInstance{}, false } // cleanupOrphanedGithubRunners will forcefully remove any github runners that appear @@ -480,7 +481,7 @@ func instanceInList(instanceName string, instances []params.Instance) (params.In // This may happen if someone manually deletes the instance in the provider. We need to // first remove the instance from github, and then from our database. func (r *basePoolManager) cleanupOrphanedGithubRunners(runners []*github.Runner) error { - poolInstanceCache := map[string][]params.Instance{} + poolInstanceCache := map[string][]commonParams.ProviderInstance{} g, ctx := errgroup.WithContext(r.ctx) for _, runner := range runners { if !r.isManagedRunner(labelsFromRunner(runner)) { @@ -513,8 +514,8 @@ func (r *basePoolManager) cleanupOrphanedGithubRunners(runners []*github.Runner) continue } - switch providerCommon.InstanceStatus(dbInstance.Status) { - case providerCommon.InstancePendingDelete, providerCommon.InstanceDeleting: + switch commonParams.InstanceStatus(dbInstance.Status) { + case commonParams.InstancePendingDelete, commonParams.InstanceDeleting: // already marked for deletion or is in the process of being deleted. // Let consolidate take care of it. continue @@ -531,7 +532,7 @@ func (r *basePoolManager) cleanupOrphanedGithubRunners(runners []*github.Runner) return fmt.Errorf("unknown provider %s for pool %s", pool.ProviderName, pool.ID) } - var poolInstances []params.Instance + var poolInstances []commonParams.ProviderInstance poolInstances, ok = poolInstanceCache[pool.ID] if !ok { r.log("updating instances cache for pool %s", pool.ID) @@ -578,7 +579,7 @@ func (r *basePoolManager) cleanupOrphanedGithubRunners(runners []*github.Runner) return nil } - if providerInstance.Status == providerCommon.InstanceRunning { + if providerInstance.Status == commonParams.InstanceRunning { // instance is running, but github reports runner as offline. Log the event. // This scenario may require manual intervention. // Perhaps it just came online and github did not yet change it's status? @@ -633,7 +634,7 @@ func (r *basePoolManager) fetchInstance(runnerName string) (params.Instance, err return runner, nil } -func (r *basePoolManager) setInstanceRunnerStatus(runnerName string, status providerCommon.RunnerStatus) (params.Instance, error) { +func (r *basePoolManager) setInstanceRunnerStatus(runnerName string, status params.RunnerStatus) (params.Instance, error) { updateParams := params.UpdateInstanceParams{ RunnerStatus: status, } @@ -658,7 +659,7 @@ func (r *basePoolManager) updateInstance(runnerName string, update params.Update return instance, nil } -func (r *basePoolManager) setInstanceStatus(runnerName string, status providerCommon.InstanceStatus, providerFault []byte) (params.Instance, error) { +func (r *basePoolManager) setInstanceStatus(runnerName string, status commonParams.InstanceStatus, providerFault []byte) (params.Instance, error) { updateParams := params.UpdateInstanceParams{ Status: status, ProviderFault: providerFault, @@ -681,8 +682,8 @@ func (r *basePoolManager) AddRunner(ctx context.Context, poolID string, aditiona createParams := params.CreateInstanceParams{ Name: name, - Status: providerCommon.InstancePendingCreate, - RunnerStatus: providerCommon.RunnerPending, + Status: commonParams.InstancePendingCreate, + RunnerStatus: params.RunnerPending, OSArch: pool.OSArch, OSType: pool.OSType, CallbackURL: r.helper.GetCallbackURL(), @@ -751,7 +752,7 @@ func (r *basePoolManager) addInstanceToProvider(instance params.Instance) error return errors.Wrap(err, "fetching instance jwt token") } - bootstrapArgs := params.BootstrapInstance{ + bootstrapArgs := commonParams.BootstrapInstance{ Name: instance.Name, Tools: r.tools, RepoURL: r.helper.GithubURL(), @@ -787,7 +788,7 @@ func (r *basePoolManager) addInstanceToProvider(instance params.Instance) error return errors.Wrap(err, "creating instance") } - if providerInstance.Status == providerCommon.InstanceError { + if providerInstance.Status == commonParams.InstanceError { instanceIDToDelete = instance.ProviderID if instanceIDToDelete == "" { instanceIDToDelete = instance.Name @@ -910,17 +911,17 @@ func (r *basePoolManager) controllerLabel() string { return fmt.Sprintf("%s%s", controllerLabelPrefix, r.controllerID) } -func (r *basePoolManager) updateArgsFromProviderInstance(providerInstance params.Instance) params.UpdateInstanceParams { +func (r *basePoolManager) updateArgsFromProviderInstance(providerInstance commonParams.ProviderInstance) params.UpdateInstanceParams { return params.UpdateInstanceParams{ ProviderID: providerInstance.ProviderID, OSName: providerInstance.OSName, OSVersion: providerInstance.OSVersion, Addresses: providerInstance.Addresses, Status: providerInstance.Status, - RunnerStatus: providerInstance.RunnerStatus, ProviderFault: providerInstance.ProviderFault, } } + func (r *basePoolManager) scaleDownOnePool(ctx context.Context, pool params.Pool) error { r.log("scaling down pool %s", pool.ID) if !pool.Enabled { @@ -939,7 +940,7 @@ func (r *basePoolManager) scaleDownOnePool(ctx context.Context, pool params.Pool // consideration for scale-down. The 5 minute grace period prevents a situation where a // "queued" workflow triggers the creation of a new idle runner, and this routine reaps // an idle runner before they have a chance to pick up a job. - if inst.RunnerStatus == providerCommon.RunnerIdle && inst.Status == providerCommon.InstanceRunning && time.Since(inst.UpdatedAt).Minutes() > 2 { + if inst.RunnerStatus == params.RunnerIdle && inst.Status == commonParams.InstanceRunning && time.Since(inst.UpdatedAt).Minutes() > 2 { idleWorkers = append(idleWorkers, inst) } } @@ -1026,7 +1027,7 @@ func (r *basePoolManager) ensureIdleRunnersForOnePool(pool params.Pool) error { idleOrPendingWorkers := []params.Instance{} for _, inst := range existingInstances { - if inst.RunnerStatus != providerCommon.RunnerActive && inst.RunnerStatus != providerCommon.RunnerTerminated { + if inst.RunnerStatus != params.RunnerActive && inst.RunnerStatus != params.RunnerTerminated { idleOrPendingWorkers = append(idleOrPendingWorkers, inst) } } @@ -1066,7 +1067,7 @@ func (r *basePoolManager) retryFailedInstancesForOnePool(ctx context.Context, po g, errCtx := errgroup.WithContext(ctx) for _, instance := range existingInstances { - if instance.Status != providerCommon.InstanceError { + if instance.Status != commonParams.InstanceError { continue } if instance.CreateAttempt >= maxCreateAttempts { @@ -1105,7 +1106,7 @@ func (r *basePoolManager) retryFailedInstancesForOnePool(ctx context.Context, po updateParams := params.UpdateInstanceParams{ CreateAttempt: instance.CreateAttempt + 1, TokenFetched: &tokenFetched, - Status: providerCommon.InstancePendingCreate, + Status: commonParams.InstancePendingCreate, } r.log("queueing previously failed instance %s for retry", instance.Name) // Set instance to pending create and wait for retry. @@ -1216,7 +1217,7 @@ func (r *basePoolManager) deletePendingInstances() error { r.log("removing instances in pending_delete") for _, instance := range instances { - if instance.Status != providerCommon.InstancePendingDelete { + if instance.Status != commonParams.InstancePendingDelete { // not in pending_delete status. Skip. continue } @@ -1230,7 +1231,7 @@ func (r *basePoolManager) deletePendingInstances() error { // Set the status to deleting before launching the goroutine that removes // the runner from the provider (which can take a long time). - if _, err := r.setInstanceStatus(instance.Name, providerCommon.InstanceDeleting, nil); err != nil { + if _, err := r.setInstanceStatus(instance.Name, commonParams.InstanceDeleting, nil); err != nil { r.log("failed to update runner %s status: %q", instance.Name, err) r.keyMux.Unlock(instance.Name, false) continue @@ -1246,7 +1247,7 @@ func (r *basePoolManager) deletePendingInstances() error { r.log("failed to remove instance %s: %s", instance.Name, err) // failed to remove from provider. Set the status back to pending_delete, which // will retry the operation. - if _, err := r.setInstanceStatus(instance.Name, providerCommon.InstancePendingDelete, nil); err != nil { + if _, err := r.setInstanceStatus(instance.Name, commonParams.InstancePendingDelete, nil); err != nil { r.log("failed to update runner %s status: %s", instance.Name, err) } } @@ -1277,7 +1278,7 @@ func (r *basePoolManager) addPendingInstances() error { return fmt.Errorf("failed to fetch instances from store: %w", err) } for _, instance := range instances { - if instance.Status != providerCommon.InstancePendingCreate { + if instance.Status != commonParams.InstancePendingCreate { // not in pending_create status. Skip. continue } @@ -1291,7 +1292,7 @@ func (r *basePoolManager) addPendingInstances() error { // Set the instance to "creating" before launching the goroutine. This will ensure that addPendingInstances() // won't attempt to create the runner a second time. - if _, err := r.setInstanceStatus(instance.Name, providerCommon.InstanceCreating, nil); err != nil { + if _, err := r.setInstanceStatus(instance.Name, commonParams.InstanceCreating, nil); err != nil { r.log("failed to update runner %s status: %s", instance.Name, err) r.keyMux.Unlock(instance.Name, false) // We failed to transition the instance to Creating. This means that garm will retry to create this instance @@ -1305,7 +1306,7 @@ func (r *basePoolManager) addPendingInstances() error { if err := r.addInstanceToProvider(instance); err != nil { r.log("failed to add instance to provider: %s", err) errAsBytes := []byte(err.Error()) - if _, err := r.setInstanceStatus(instance.Name, providerCommon.InstanceError, errAsBytes); err != nil { + if _, err := r.setInstanceStatus(instance.Name, commonParams.InstanceError, errAsBytes); err != nil { r.log("failed to update runner %s status: %s", instance.Name, err) } r.log("failed to create instance in provider: %s", err) @@ -1431,7 +1432,7 @@ func (r *basePoolManager) ForceDeleteRunner(runner params.Instance) error { } r.log("setting instance status for: %v", runner.Name) - if _, err := r.setInstanceStatus(runner.Name, providerCommon.InstancePendingDelete, nil); err != nil { + if _, err := r.setInstanceStatus(runner.Name, commonParams.InstancePendingDelete, nil); err != nil { r.log("failed to update runner %s status: %s", runner.Name, err) return errors.Wrap(err, "updating runner") } diff --git a/runner/pool/repository.go b/runner/pool/repository.go index 093d0118..86dc5cec 100644 --- a/runner/pool/repository.go +++ b/runner/pool/repository.go @@ -21,8 +21,8 @@ import ( "strings" "sync" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" dbCommon "github.com/cloudbase/garm/database/common" - runnerErrors "github.com/cloudbase/garm/errors" "github.com/cloudbase/garm/params" "github.com/cloudbase/garm/runner/common" "github.com/cloudbase/garm/util" diff --git a/runner/pool/util.go b/runner/pool/util.go index 3854891b..4a8c09e3 100644 --- a/runner/pool/util.go +++ b/runner/pool/util.go @@ -7,7 +7,7 @@ import ( "sync" "sync/atomic" - runnerErrors "github.com/cloudbase/garm/errors" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/params" ) diff --git a/runner/pools.go b/runner/pools.go index 58dce91b..8fbe2b0e 100644 --- a/runner/pools.go +++ b/runner/pools.go @@ -18,8 +18,8 @@ import ( "context" "fmt" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/auth" - runnerErrors "github.com/cloudbase/garm/errors" "github.com/cloudbase/garm/params" "github.com/pkg/errors" diff --git a/runner/pools_test.go b/runner/pools_test.go index b83c69a2..db112b69 100644 --- a/runner/pools_test.go +++ b/runner/pools_test.go @@ -19,11 +19,11 @@ import ( "fmt" "testing" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/auth" "github.com/cloudbase/garm/config" "github.com/cloudbase/garm/database" dbCommon "github.com/cloudbase/garm/database/common" - runnerErrors "github.com/cloudbase/garm/errors" garmTesting "github.com/cloudbase/garm/internal/testing" "github.com/cloudbase/garm/params" "github.com/cloudbase/garm/runner/common" diff --git a/runner/providers/common/common.go b/runner/providers/common/common.go deleted file mode 100644 index dfa49f0d..00000000 --- a/runner/providers/common/common.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2022 Cloudbase Solutions SRL -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package common - -type InstanceStatus string -type RunnerStatus string - -const ( - InstanceRunning InstanceStatus = "running" - InstanceStopped InstanceStatus = "stopped" - InstanceError InstanceStatus = "error" - InstancePendingDelete InstanceStatus = "pending_delete" - InstanceDeleting InstanceStatus = "deleting" - InstancePendingCreate InstanceStatus = "pending_create" - InstanceCreating InstanceStatus = "creating" - InstanceStatusUnknown InstanceStatus = "unknown" - - RunnerIdle RunnerStatus = "idle" - RunnerPending RunnerStatus = "pending" - RunnerTerminated RunnerStatus = "terminated" - RunnerInstalling RunnerStatus = "installing" - RunnerFailed RunnerStatus = "failed" - RunnerActive RunnerStatus = "active" -) - -// IsValidStatus checks if the given status is valid. -func IsValidStatus(status InstanceStatus) bool { - switch status { - case InstanceRunning, InstanceError, InstancePendingCreate, - InstancePendingDelete, InstanceStatusUnknown, InstanceStopped, - InstanceCreating, InstanceDeleting: - - return true - default: - return false - } -} - -// IsProviderValidStatus checks if the given status is valid for the provider. -// A provider should only return a status indicating that the instance is in a -// lifecycle state that it can influence. The sole purpose of a provider is to -// manage the lifecycle of an instance. Statuses that indicate an instance should -// be created or removed, will be set by the controller. -func IsValidProviderStatus(status InstanceStatus) bool { - switch status { - case InstanceRunning, InstanceError, InstanceStopped: - return true - default: - return false - } -} diff --git a/runner/providers/external/execution/exit_codes.go b/runner/providers/external/execution/exit_codes.go deleted file mode 100644 index 40aefb37..00000000 --- a/runner/providers/external/execution/exit_codes.go +++ /dev/null @@ -1,26 +0,0 @@ -package execution - -import ( - "errors" - - gErrors "github.com/cloudbase/garm/errors" -) - -const ( - // ExitCodeNotFound is an exit code that indicates a Not Found error - ExitCodeNotFound int = 30 - // ExitCodeDuplicate is an exit code that indicates a duplicate error - ExitCodeDuplicate int = 31 -) - -func ResolveErrorToExitCode(err error) int { - if err != nil { - if errors.Is(err, gErrors.ErrNotFound) { - return ExitCodeNotFound - } else if errors.Is(err, gErrors.ErrDuplicateEntity) { - return ExitCodeDuplicate - } - return 1 - } - return 0 -} diff --git a/runner/providers/external/external.go b/runner/providers/external/external.go index 1c2ec1f2..c1bd7141 100644 --- a/runner/providers/external/external.go +++ b/runner/providers/external/external.go @@ -7,13 +7,15 @@ import ( "log" "os/exec" + "github.com/cloudbase/garm-provider-common/execution" + + commonParams "github.com/cloudbase/garm-provider-common/params" + + garmErrors "github.com/cloudbase/garm-provider-common/errors" + garmExec "github.com/cloudbase/garm-provider-common/util/exec" "github.com/cloudbase/garm/config" - garmErrors "github.com/cloudbase/garm/errors" "github.com/cloudbase/garm/params" "github.com/cloudbase/garm/runner/common" - providerCommon "github.com/cloudbase/garm/runner/providers/common" - "github.com/cloudbase/garm/runner/providers/external/execution" - garmExec "github.com/cloudbase/garm/util/exec" "github.com/pkg/errors" ) @@ -44,7 +46,7 @@ type external struct { execPath string } -func (e *external) validateResult(inst params.Instance) error { +func (e *external) validateResult(inst commonParams.ProviderInstance) error { if inst.ProviderID == "" { return garmErrors.NewProviderError("missing provider ID") } @@ -57,7 +59,7 @@ func (e *external) validateResult(inst params.Instance) error { // we can still function without this info (I think) log.Printf("WARNING: missing OS information") } - if !providerCommon.IsValidProviderStatus(inst.Status) { + if !IsValidProviderStatus(inst.Status) { return garmErrors.NewProviderError("invalid status returned (%s)", inst.Status) } @@ -65,7 +67,7 @@ func (e *external) validateResult(inst params.Instance) error { } // CreateInstance creates a new compute instance in the provider. -func (e *external) CreateInstance(ctx context.Context, bootstrapParams params.BootstrapInstance) (params.Instance, error) { +func (e *external) CreateInstance(ctx context.Context, bootstrapParams commonParams.BootstrapInstance) (commonParams.ProviderInstance, error) { asEnv := []string{ fmt.Sprintf("GARM_COMMAND=%s", execution.CreateInstanceCommand), fmt.Sprintf("GARM_CONTROLLER_ID=%s", e.controllerID), @@ -75,21 +77,21 @@ func (e *external) CreateInstance(ctx context.Context, bootstrapParams params.Bo asJs, err := json.Marshal(bootstrapParams) if err != nil { - return params.Instance{}, errors.Wrap(err, "serializing bootstrap params") + return commonParams.ProviderInstance{}, errors.Wrap(err, "serializing bootstrap params") } out, err := garmExec.Exec(ctx, e.execPath, asJs, asEnv) if err != nil { - return params.Instance{}, garmErrors.NewProviderError("provider binary %s returned error: %s", e.execPath, err) + return commonParams.ProviderInstance{}, garmErrors.NewProviderError("provider binary %s returned error: %s", e.execPath, err) } - var param params.Instance + var param commonParams.ProviderInstance if err := json.Unmarshal(out, ¶m); err != nil { - return params.Instance{}, garmErrors.NewProviderError("failed to decode response from binary: %s", err) + return commonParams.ProviderInstance{}, garmErrors.NewProviderError("failed to decode response from binary: %s", err) } if err := e.validateResult(param); err != nil { - return params.Instance{}, garmErrors.NewProviderError("failed to validate result: %s", err) + return commonParams.ProviderInstance{}, garmErrors.NewProviderError("failed to validate result: %s", err) } retAsJs, _ := json.MarshalIndent(param, "", " ") @@ -118,7 +120,7 @@ func (e *external) DeleteInstance(ctx context.Context, instance string) error { } // GetInstance will return details about one instance. -func (e *external) GetInstance(ctx context.Context, instance string) (params.Instance, error) { +func (e *external) GetInstance(ctx context.Context, instance string) (commonParams.ProviderInstance, error) { asEnv := []string{ fmt.Sprintf("GARM_COMMAND=%s", execution.GetInstanceCommand), fmt.Sprintf("GARM_CONTROLLER_ID=%s", e.controllerID), @@ -130,23 +132,23 @@ func (e *external) GetInstance(ctx context.Context, instance string) (params.Ins // know when the error is ErrNotFound. out, err := garmExec.Exec(ctx, e.execPath, nil, asEnv) if err != nil { - return params.Instance{}, garmErrors.NewProviderError("provider binary %s returned error: %s", e.execPath, err) + return commonParams.ProviderInstance{}, garmErrors.NewProviderError("provider binary %s returned error: %s", e.execPath, err) } - var param params.Instance + var param commonParams.ProviderInstance if err := json.Unmarshal(out, ¶m); err != nil { - return params.Instance{}, garmErrors.NewProviderError("failed to decode response from binary: %s", err) + return commonParams.ProviderInstance{}, garmErrors.NewProviderError("failed to decode response from binary: %s", err) } if err := e.validateResult(param); err != nil { - return params.Instance{}, garmErrors.NewProviderError("failed to validate result: %s", err) + return commonParams.ProviderInstance{}, garmErrors.NewProviderError("failed to validate result: %s", err) } return param, nil } // ListInstances will list all instances for a provider. -func (e *external) ListInstances(ctx context.Context, poolID string) ([]params.Instance, error) { +func (e *external) ListInstances(ctx context.Context, poolID string) ([]commonParams.ProviderInstance, error) { asEnv := []string{ fmt.Sprintf("GARM_COMMAND=%s", execution.ListInstancesCommand), fmt.Sprintf("GARM_CONTROLLER_ID=%s", e.controllerID), @@ -156,20 +158,22 @@ func (e *external) ListInstances(ctx context.Context, poolID string) ([]params.I out, err := garmExec.Exec(ctx, e.execPath, nil, asEnv) if err != nil { - return []params.Instance{}, garmErrors.NewProviderError("provider binary %s returned error: %s", e.execPath, err) + return []commonParams.ProviderInstance{}, garmErrors.NewProviderError("provider binary %s returned error: %s", e.execPath, err) } - var param []params.Instance + var param []commonParams.ProviderInstance if err := json.Unmarshal(out, ¶m); err != nil { - return []params.Instance{}, garmErrors.NewProviderError("failed to decode response from binary: %s", err) + return []commonParams.ProviderInstance{}, garmErrors.NewProviderError("failed to decode response from binary: %s", err) } - for _, inst := range param { + ret := make([]commonParams.ProviderInstance, len(param)) + for idx, inst := range param { if err := e.validateResult(inst); err != nil { - return []params.Instance{}, garmErrors.NewProviderError("failed to validate result: %s", err) + return []commonParams.ProviderInstance{}, garmErrors.NewProviderError("failed to validate result: %s", err) } + ret[idx] = inst } - return param, nil + return ret, nil } // RemoveAllInstances will remove all instances created by this provider. diff --git a/runner/providers/external/util.go b/runner/providers/external/util.go new file mode 100644 index 00000000..460714e9 --- /dev/null +++ b/runner/providers/external/util.go @@ -0,0 +1,21 @@ +package external + +import ( + commonParams "github.com/cloudbase/garm-provider-common/params" +) + +// IsProviderValidStatus checks if the given status is valid for the provider. +// A provider should only return a status indicating that the instance is in a +// lifecycle state that it can influence. The sole purpose of a provider is to +// manage the lifecycle of an instance. Statuses that indicate an instance should +// be created or removed, will be set by the controller. +func IsValidProviderStatus(status commonParams.InstanceStatus) bool { + switch status { + case commonParams.InstanceRunning, commonParams.InstanceError, + commonParams.InstanceStopped, commonParams.InstanceStatusUnknown: + + return true + default: + return false + } +} diff --git a/runner/providers/lxd/images.go b/runner/providers/lxd/images.go index 8e407c56..faf88b98 100644 --- a/runner/providers/lxd/images.go +++ b/runner/providers/lxd/images.go @@ -18,8 +18,8 @@ import ( "fmt" "strings" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/config" - runnerErrors "github.com/cloudbase/garm/errors" lxd "github.com/lxc/lxd/client" "github.com/lxc/lxd/shared/api" diff --git a/runner/providers/lxd/lxd.go b/runner/providers/lxd/lxd.go index 33b99716..1e02f6eb 100644 --- a/runner/providers/lxd/lxd.go +++ b/runner/providers/lxd/lxd.go @@ -21,16 +21,18 @@ import ( "sync" "time" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/config" - runnerErrors "github.com/cloudbase/garm/errors" "github.com/cloudbase/garm/params" "github.com/cloudbase/garm/runner/common" - "github.com/cloudbase/garm/util" "github.com/google/go-github/v53/github" lxd "github.com/lxc/lxd/client" "github.com/lxc/lxd/shared/api" "github.com/pkg/errors" + + "github.com/cloudbase/garm-provider-common/cloudconfig" + commonParams "github.com/cloudbase/garm-provider-common/params" ) var _ common.Provider = &LXD{} @@ -66,16 +68,16 @@ var ( "arm64": "arm64", } - configToLXDArchMap map[params.OSArch]string = map[params.OSArch]string{ - params.Amd64: "x86_64", - params.Arm64: "aarch64", - params.Arm: "armv7l", + configToLXDArchMap map[commonParams.OSArch]string = map[commonParams.OSArch]string{ + commonParams.Amd64: "x86_64", + commonParams.Arm64: "aarch64", + commonParams.Arm: "armv7l", } - lxdToConfigArch map[string]params.OSArch = map[string]params.OSArch{ - "x86_64": params.Amd64, - "aarch64": params.Arm64, - "armv7l": params.Arm, + lxdToConfigArch map[string]commonParams.OSArch = map[string]commonParams.OSArch{ + "x86_64": commonParams.Amd64, + "aarch64": commonParams.Arm64, + "armv7l": commonParams.Arm, } ) @@ -171,10 +173,10 @@ func (l *LXD) getProfiles(flavor string) ([]string, error) { return ret, nil } -func (l *LXD) getTools(tools []*github.RunnerApplicationDownload, osType params.OSType, architecture string) (github.RunnerApplicationDownload, error) { +func (l *LXD) getTools(tools []*github.RunnerApplicationDownload, osType commonParams.OSType, architecture string) (github.RunnerApplicationDownload, error) { // Validate image OS. Linux only for now. switch osType { - case params.Linux: + case commonParams.Linux: default: return github.RunnerApplicationDownload{}, fmt.Errorf("this provider does not support OS type: %s", osType) } @@ -210,7 +212,7 @@ func (l *LXD) secureBootEnabled() string { return "false" } -func (l *LXD) getCreateInstanceArgs(bootstrapParams params.BootstrapInstance, specs extraSpecs) (api.InstancesPost, error) { +func (l *LXD) getCreateInstanceArgs(bootstrapParams commonParams.BootstrapInstance, specs extraSpecs) (api.InstancesPost, error) { if bootstrapParams.Name == "" { return api.InstancesPost{}, runnerErrors.NewBadRequestError("missing name") } @@ -237,7 +239,7 @@ func (l *LXD) getCreateInstanceArgs(bootstrapParams params.BootstrapInstance, sp bootstrapParams.UserDataOptions.DisableUpdatesOnBoot = specs.DisableUpdates bootstrapParams.UserDataOptions.ExtraPackages = specs.ExtraPackages - cloudCfg, err := util.GetCloudConfig(bootstrapParams, tools, bootstrapParams.Name) + cloudCfg, err := cloudconfig.GetCloudConfig(bootstrapParams, tools, bootstrapParams.Name) if err != nil { return api.InstancesPost{}, errors.Wrap(err, "generating cloud-config") } @@ -313,40 +315,40 @@ func (l *LXD) launchInstance(createArgs api.InstancesPost) error { } // CreateInstance creates a new compute instance in the provider. -func (l *LXD) CreateInstance(ctx context.Context, bootstrapParams params.BootstrapInstance) (params.Instance, error) { +func (l *LXD) CreateInstance(ctx context.Context, bootstrapParams commonParams.BootstrapInstance) (commonParams.ProviderInstance, error) { extraSpecs, err := parseExtraSpecsFromBootstrapParams(bootstrapParams) if err != nil { - return params.Instance{}, errors.Wrap(err, "parsing extra specs") + return commonParams.ProviderInstance{}, errors.Wrap(err, "parsing extra specs") } args, err := l.getCreateInstanceArgs(bootstrapParams, extraSpecs) if err != nil { - return params.Instance{}, errors.Wrap(err, "fetching create args") + return commonParams.ProviderInstance{}, errors.Wrap(err, "fetching create args") } if err := l.launchInstance(args); err != nil { - return params.Instance{}, errors.Wrap(err, "creating instance") + return commonParams.ProviderInstance{}, errors.Wrap(err, "creating instance") } ret, err := l.waitInstanceHasIP(ctx, args.Name) if err != nil { - return params.Instance{}, errors.Wrap(err, "fetching instance") + return commonParams.ProviderInstance{}, errors.Wrap(err, "fetching instance") } return ret, nil } // GetInstance will return details about one instance. -func (l *LXD) GetInstance(ctx context.Context, instanceName string) (params.Instance, error) { +func (l *LXD) GetInstance(ctx context.Context, instanceName string) (commonParams.ProviderInstance, error) { cli, err := l.getCLI() if err != nil { - return params.Instance{}, errors.Wrap(err, "fetching client") + return commonParams.ProviderInstance{}, errors.Wrap(err, "fetching client") } instance, _, err := cli.GetInstanceFull(instanceName) if err != nil { if isNotFoundError(err) { - return params.Instance{}, errors.Wrapf(runnerErrors.ErrNotFound, "fetching instance: %q", err) + return commonParams.ProviderInstance{}, errors.Wrapf(runnerErrors.ErrNotFound, "fetching instance: %q", err) } - return params.Instance{}, errors.Wrap(err, "fetching instance") + return commonParams.ProviderInstance{}, errors.Wrap(err, "fetching instance") } return lxdInstanceToAPIInstance(instance), nil @@ -418,10 +420,10 @@ type listResponse struct { } // ListInstances will list all instances for a provider. -func (l *LXD) ListInstances(ctx context.Context, poolID string) ([]params.Instance, error) { +func (l *LXD) ListInstances(ctx context.Context, poolID string) ([]commonParams.ProviderInstance, error) { cli, err := l.getCLI() if err != nil { - return []params.Instance{}, errors.Wrap(err, "fetching client") + return []commonParams.ProviderInstance{}, errors.Wrap(err, "fetching client") } result := make(chan listResponse, 1) @@ -443,14 +445,14 @@ func (l *LXD) ListInstances(ctx context.Context, poolID string) ([]params.Instan select { case res := <-result: if res.err != nil { - return []params.Instance{}, errors.Wrap(res.err, "fetching instances") + return []commonParams.ProviderInstance{}, errors.Wrap(res.err, "fetching instances") } instances = res.instances case <-time.After(time.Second * 60): - return []params.Instance{}, errors.Wrap(runnerErrors.ErrTimeout, "fetching instances from provider") + return []commonParams.ProviderInstance{}, errors.Wrap(runnerErrors.ErrTimeout, "fetching instances from provider") } - ret := []params.Instance{} + ret := []commonParams.ProviderInstance{} for _, instance := range instances { if id, ok := instance.ExpandedConfig[controllerIDKeyName]; ok && id == l.controllerID { diff --git a/runner/providers/lxd/specs.go b/runner/providers/lxd/specs.go index 202473b7..0471a536 100644 --- a/runner/providers/lxd/specs.go +++ b/runner/providers/lxd/specs.go @@ -17,7 +17,7 @@ package lxd import ( "encoding/json" - "github.com/cloudbase/garm/params" + commonParams "github.com/cloudbase/garm-provider-common/params" "github.com/pkg/errors" ) @@ -26,7 +26,7 @@ type extraSpecs struct { ExtraPackages []string `json:"extra_packages"` } -func parseExtraSpecsFromBootstrapParams(bootstrapParams params.BootstrapInstance) (extraSpecs, error) { +func parseExtraSpecsFromBootstrapParams(bootstrapParams commonParams.BootstrapInstance) (extraSpecs, error) { specs := extraSpecs{} if bootstrapParams.ExtraSpecs == nil { return specs, nil diff --git a/runner/providers/lxd/util.go b/runner/providers/lxd/util.go index f029037d..2168bcec 100644 --- a/runner/providers/lxd/util.go +++ b/runner/providers/lxd/util.go @@ -25,10 +25,10 @@ import ( "strings" "time" + commonParams "github.com/cloudbase/garm-provider-common/params" + + "github.com/cloudbase/garm-provider-common/util" "github.com/cloudbase/garm/config" - "github.com/cloudbase/garm/params" - "github.com/cloudbase/garm/runner/providers/common" - "github.com/cloudbase/garm/util" "github.com/juju/clock" "github.com/juju/retry" @@ -61,7 +61,7 @@ func isNotFoundError(err error) bool { return false } -func lxdInstanceToAPIInstance(instance *api.InstanceFull) params.Instance { +func lxdInstanceToAPIInstance(instance *api.InstanceFull) commonParams.ProviderInstance { lxdOS, ok := instance.ExpandedConfig["image.os"] if !ok { log.Printf("failed to find OS in instance config") @@ -77,7 +77,7 @@ func lxdInstanceToAPIInstance(instance *api.InstanceFull) params.Instance { if !ok { log.Printf("failed to find OS type in fallback location") } - osType = params.OSType(osTypeFromTag) + osType = commonParams.OSType(osTypeFromTag) } osRelease, ok := instance.ExpandedConfig["image.release"] @@ -86,16 +86,16 @@ func lxdInstanceToAPIInstance(instance *api.InstanceFull) params.Instance { } state := instance.State - addresses := []params.Address{} + addresses := []commonParams.Address{} if state.Network != nil { for _, details := range state.Network { for _, addr := range details.Addresses { if addr.Scope != "global" { continue } - addresses = append(addresses, params.Address{ + addresses = append(addresses, commonParams.Address{ Address: addr.Address, - Type: params.PublicAddress, + Type: commonParams.PublicAddress, }) } } @@ -106,7 +106,7 @@ func lxdInstanceToAPIInstance(instance *api.InstanceFull) params.Instance { log.Printf("failed to find OS architecture") } - return params.Instance{ + return commonParams.ProviderInstance{ OSArch: instanceArch, ProviderID: instance.Name, Name: instance.Name, @@ -118,14 +118,14 @@ func lxdInstanceToAPIInstance(instance *api.InstanceFull) params.Instance { } } -func lxdStatusToProviderStatus(status string) common.InstanceStatus { +func lxdStatusToProviderStatus(status string) commonParams.InstanceStatus { switch status { case "Running": - return common.InstanceRunning + return commonParams.InstanceRunning case "Stopped": - return common.InstanceStopped + return commonParams.InstanceStopped default: - return common.InstanceStatusUnknown + return commonParams.InstanceStatusUnknown } } @@ -186,9 +186,9 @@ func projectName(cfg config.LXD) string { return DefaultProjectName } -func resolveArchitecture(osArch params.OSArch) (string, error) { +func resolveArchitecture(osArch commonParams.OSArch) (string, error) { if string(osArch) == "" { - return configToLXDArchMap[params.Amd64], nil + return configToLXDArchMap[commonParams.Amd64], nil } arch, ok := configToLXDArchMap[osArch] if !ok { @@ -199,8 +199,8 @@ func resolveArchitecture(osArch params.OSArch) (string, error) { // waitDeviceActive is a function capable of figuring out when a Equinix Metal // device is active -func (l *LXD) waitInstanceHasIP(ctx context.Context, instanceName string) (params.Instance, error) { - var p params.Instance +func (l *LXD) waitInstanceHasIP(ctx context.Context, instanceName string) (commonParams.ProviderInstance, error) { + var p commonParams.ProviderInstance var errIPNotFound error = fmt.Errorf("ip not found") err := retry.Call(retry.CallArgs{ Func: func() error { @@ -227,7 +227,7 @@ func (l *LXD) waitInstanceHasIP(ctx context.Context, instanceName string) (param }) if err != nil && err != errIPNotFound { - return params.Instance{}, err + return commonParams.ProviderInstance{}, err } return p, nil diff --git a/runner/repositories.go b/runner/repositories.go index 85369f28..cf5191dd 100644 --- a/runner/repositories.go +++ b/runner/repositories.go @@ -20,8 +20,8 @@ import ( "log" "strings" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/auth" - runnerErrors "github.com/cloudbase/garm/errors" "github.com/cloudbase/garm/params" "github.com/cloudbase/garm/runner/common" "github.com/cloudbase/garm/util/appdefaults" diff --git a/runner/repositories_test.go b/runner/repositories_test.go index 809be125..0b2c527a 100644 --- a/runner/repositories_test.go +++ b/runner/repositories_test.go @@ -19,11 +19,11 @@ import ( "fmt" "testing" + runnerErrors "github.com/cloudbase/garm-provider-common/errors" "github.com/cloudbase/garm/auth" "github.com/cloudbase/garm/config" "github.com/cloudbase/garm/database" dbCommon "github.com/cloudbase/garm/database/common" - runnerErrors "github.com/cloudbase/garm/errors" garmTesting "github.com/cloudbase/garm/internal/testing" "github.com/cloudbase/garm/params" "github.com/cloudbase/garm/runner/common" diff --git a/runner/runner.go b/runner/runner.go index 55753542..b8120adc 100644 --- a/runner/runner.go +++ b/runner/runner.go @@ -29,16 +29,17 @@ import ( "sync" "time" + commonParams "github.com/cloudbase/garm-provider-common/params" + + runnerErrors "github.com/cloudbase/garm-provider-common/errors" + "github.com/cloudbase/garm-provider-common/util" "github.com/cloudbase/garm/auth" "github.com/cloudbase/garm/config" dbCommon "github.com/cloudbase/garm/database/common" - runnerErrors "github.com/cloudbase/garm/errors" "github.com/cloudbase/garm/params" "github.com/cloudbase/garm/runner/common" "github.com/cloudbase/garm/runner/pool" "github.com/cloudbase/garm/runner/providers" - providerCommon "github.com/cloudbase/garm/runner/providers/common" - "github.com/cloudbase/garm/util" "golang.org/x/sync/errgroup" "github.com/google/uuid" @@ -761,7 +762,7 @@ func (r *Runner) appendTagsToCreatePoolParams(param params.CreatePoolParams) (pa return param, nil } -func (r *Runner) processTags(osArch string, osType params.OSType, tags []string) ([]string, error) { +func (r *Runner) processTags(osArch string, osType commonParams.OSType, tags []string) ([]string, error) { // github automatically adds the "self-hosted" tag as well as the OS type (linux, windows, etc) // and architecture (arm, x64, etc) to all self hosted runners. When a workflow job comes in, we try // to find a pool based on the labels that are set in the workflow. If we don't explicitly define these @@ -857,7 +858,7 @@ func (r *Runner) GetInstanceGithubRegistrationToken(ctx context.Context) (string } status := auth.InstanceRunnerStatus(ctx) - if status != providerCommon.RunnerPending && status != providerCommon.RunnerInstalling { + if status != params.RunnerPending && status != params.RunnerInstalling { return "", runnerErrors.ErrUnauthorized } @@ -943,9 +944,9 @@ func (r *Runner) ForceDeleteRunner(ctx context.Context, instanceName string) err } switch instance.Status { - case providerCommon.InstanceRunning, providerCommon.InstanceError: + case commonParams.InstanceRunning, commonParams.InstanceError: default: - return runnerErrors.NewBadRequestError("runner must be in %q or %q state", providerCommon.InstanceRunning, providerCommon.InstanceError) + return runnerErrors.NewBadRequestError("runner must be in %q or %q state", commonParams.InstanceRunning, commonParams.InstanceError) } poolMgr, err := r.getPoolManagerFromInstance(ctx, instance) diff --git a/runner/types.go b/runner/types.go index 3a081e09..1fb38bb7 100644 --- a/runner/types.go +++ b/runner/types.go @@ -14,7 +14,7 @@ package runner -import "github.com/cloudbase/garm/params" +import "github.com/cloudbase/garm-provider-common/params" type HookTargetType string diff --git a/scripts/build-static.sh b/scripts/build-static.sh index debcd5e4..cafa6a55 100755 --- a/scripts/build-static.sh +++ b/scripts/build-static.sh @@ -10,12 +10,34 @@ export CGO_ENABLED=1 USER_ID=${USER_ID:-$UID} USER_GROUP=${USER_GROUP:-$(id -g)} +mkdir -p $BIN_DIR/amd64 $BIN_DIR/arm64 cd $GARM_SOURCE/cmd/garm -go build -mod vendor -o $BIN_DIR/garm -tags osusergo,netgo,sqlite_omit_load_extension -ldflags "-linkmode external -extldflags '-static' -s -w -X main.Version=$(git describe --tags --match='v[0-9]*' --dirty --always)" . -# GOOS=windows CC=x86_64-w64-mingw32-cc go build -mod vendor -o $BIN_DIR/garm.exe -tags osusergo,netgo,sqlite_omit_load_extension -ldflags "-s -w -X main.Version=$(git describe --always --dirty)" . +go build -mod vendor \ + -o $BIN_DIR/amd64/garm \ + -tags osusergo,netgo,sqlite_omit_load_extension \ + -ldflags "-linkmode external -extldflags '-static' -s -w -X main.Version=$(git describe --tags --match='v[0-9]*' --dirty --always)" . +CC=aarch64-linux-musl-gcc GOARCH=arm64 go build \ + -mod vendor \ + -o $BIN_DIR/arm64/garm \ + -tags osusergo,netgo,sqlite_omit_load_extension \ + -ldflags "-linkmode external -extldflags '-static' -s -w -X main.Version=$(git describe --tags --match='v[0-9]*' --dirty --always)" . +# GOOS=windows CC=x86_64-w64-mingw32-cc go build -mod vendor \ +# -o $BIN_DIR/amd64/garm.exe \ +# -tags osusergo,netgo,sqlite_omit_load_extension \ +# -ldflags "-s -w -X main.Version=$(git describe --tags --match='v[0-9]*' --dirty --always)" . cd $GARM_SOURCE/cmd/garm-cli -go build -mod vendor -o $BIN_DIR/garm-cli -tags osusergo,netgo -ldflags "-linkmode external -extldflags '-static' -s -w -X garm/cmd/garm-cli/cmd.Version=$(git describe --tags --match='v[0-9]*' --dirty --always)" . -# GOOS=windows CGO_ENABLED=0 go build -mod vendor -o $BIN_DIR/garm-cli.exe -ldflags "-s -w -X garm/cmd/garm-cli/cmd.Version=$(git describe --always --dirty)" . +go build -mod vendor \ + -o $BIN_DIR/amd64/garm-cli \ + -tags osusergo,netgo,sqlite_omit_load_extension \ + -ldflags "-linkmode external -extldflags '-static' -s -w -X github.com/cloudbase/garm/cmd/garm-cli/cmd.Version=$(git describe --tags --match='v[0-9]*' --dirty --always)" . +CC=aarch64-linux-musl-gcc GOARCH=arm64 go build -mod vendor \ + -o $BIN_DIR/arm64/garm-cli \ + -tags osusergo,netgo,sqlite_omit_load_extension \ + -ldflags "-linkmode external -extldflags '-static' -s -w -X github.com/cloudbase/garm/cmd/garm-cli/cmd.Version=$(git describe --tags --match='v[0-9]*' --dirty --always)" . +# GOOS=windows CGO_ENABLED=0 go build -mod vendor \ +# -o $BIN_DIR/amd64/garm-cli.exe \ +# -tags osusergo,netgo,sqlite_omit_load_extension \ +# -ldflags "-s -w -X github.com/cloudbase/garm/cmd/garm-cli/cmd.Version=$(git describe --tags --match='v[0-9]*' --dirty --always)" . chown $USER_ID:$USER_GROUP -R "$BIN_DIR" diff --git a/testdata/config.toml b/testdata/config.toml index 1182ad4a..c0532d8e 100644 --- a/testdata/config.toml +++ b/testdata/config.toml @@ -17,16 +17,15 @@ callback_url = "https://garm.example.com/api/v1/callbacks/status" # highly encouraged. metadata_url = "https://garm.example.com/api/v1/metadata" -# This folder is defined here for future use. Right now, we create a SSH -# public/private key-pair. -config_dir = "/etc/garm" - # Uncomment this line if you'd like to log to a file instead of standard output. # log_file = "/tmp/runner-manager.log" # Enable streaming logs via web sockets. Use garm-cli debug-log. enable_log_streamer = false +# Enable the golang debug server. See the documentation in the "doc" folder for more information. +debug_server = false + [metrics] # Toggle metrics. If set to false, the API endpoint for metrics collection will # be disabled. @@ -78,34 +77,21 @@ time_to_live = "8760h" debug = false # Database backend to use. Currently supported backends are: # * sqlite3 - # * mysql backend = "sqlite3" # the passphrase option is a temporary measure by which we encrypt the webhook # secret that gets saved to the database, using AES256. In the future, secrets # will be saved to something like Barbican or Vault, eliminating the need for # this. This setting needs to be 32 characters in size. passphrase = "shreotsinWadquidAitNefayctowUrph" - [database.mysql] - # If MySQL is used, these are the credentials and connection information used - # to connect to the server instance. - # database username - username = "" - # Database password - password = "" - # hostname to connect to - hostname = "" - # database name - database = "" [database.sqlite3] # Path on disk to the sqlite3 database file. db_file = "/etc/garm/garm.db" - # Currently, providers are defined statically in the config. This is due to the fact # that we have not yet added support for storing secrets in something like Barbican # or Vault. This will change in the future. However, for now, it's important to remember # that once you create a pool using one of the providers defined here, the name of that -# provider must not be changes, or the pool will no longer work. Make sure you remove any +# provider must not be changed, or the pool will no longer work. Make sure you remove any # pools before removing or changing a provider. [[provider]] # An arbitrary string describing this provider. @@ -135,7 +121,7 @@ time_to_live = "8760h" # * virtual-machine (default) # * container # - instance_type = "virtual-machine" + instance_type = "container" # enable/disable secure boot. If the image you select for the pool does not have a # signed bootloader, set this to false, otherwise your instances won't boot. secure_boot = false diff --git a/util/appdefaults/appdefaults.go b/util/appdefaults/appdefaults.go index 70b779bc..d0d86976 100644 --- a/util/appdefaults/appdefaults.go +++ b/util/appdefaults/appdefaults.go @@ -19,11 +19,6 @@ const ( // configuration file. DefaultConfigFilePath = "/etc/garm/config.toml" - // DefaultUser is the default username that should exist on the instances. - DefaultUser = "runner" - // DefaultUserShell is the shell for the default user. - DefaultUserShell = "/bin/bash" - // DefaultPoolQueueSize is the default size for a pool queue. DefaultPoolQueueSize = 10 @@ -33,16 +28,3 @@ const ( // uploadBaseURL is the default URL for guthub uploads. GithubDefaultUploadBaseURL = "https://uploads.github.com/" ) - -var ( - // DefaultConfigDir is the default path on disk to the config dir. The config - // file will probably be in the same folder, but it is not mandatory. - DefaultConfigDir = "/etc/garm" - - // DefaultUserGroups are the groups the default user will be part of. - DefaultUserGroups = []string{ - "sudo", "adm", "cdrom", "dialout", - "dip", "video", "plugdev", "netdev", - "docker", "lxd", - } -) diff --git a/util/util.go b/util/util.go index bf8f29ac..db2b86f0 100644 --- a/util/util.go +++ b/util/util.go @@ -15,186 +15,20 @@ package util import ( - "bytes" - "compress/gzip" "context" - "crypto/aes" - "crypto/cipher" - "crypto/rand" "crypto/tls" "crypto/x509" - "encoding/base64" - "encoding/binary" "fmt" - "io" - "math/big" "net/http" - "os" - "path" - "regexp" - "strings" - "unicode" - "unicode/utf16" - "github.com/cloudbase/garm/cloudconfig" - "github.com/cloudbase/garm/config" - runnerErrors "github.com/cloudbase/garm/errors" "github.com/cloudbase/garm/params" "github.com/cloudbase/garm/runner/common" - "github.com/cloudbase/garm/util/appdefaults" "github.com/google/go-github/v53/github" - "github.com/google/uuid" - gorillaHandlers "github.com/gorilla/handlers" "github.com/pkg/errors" - "github.com/teris-io/shortid" - "golang.org/x/crypto/bcrypt" "golang.org/x/oauth2" - lumberjack "gopkg.in/natefinch/lumberjack.v2" ) -const alphanumeric = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" - -// From: https://www.alexedwards.net/blog/validation-snippets-for-go#email-validation -var rxEmail = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") - -var ( - OSToOSTypeMap map[string]params.OSType = map[string]params.OSType{ - "almalinux": params.Linux, - "alma": params.Linux, - "alpine": params.Linux, - "archlinux": params.Linux, - "arch": params.Linux, - "centos": params.Linux, - "ubuntu": params.Linux, - "rhel": params.Linux, - "suse": params.Linux, - "opensuse": params.Linux, - "fedora": params.Linux, - "debian": params.Linux, - "flatcar": params.Linux, - "gentoo": params.Linux, - "rockylinux": params.Linux, - "rocky": params.Linux, - "windows": params.Windows, - } - - githubArchMapping map[string]string = map[string]string{ - "x86_64": "x64", - "amd64": "x64", - "armv7l": "arm", - "aarch64": "arm64", - "x64": "x64", - "arm": "arm", - "arm64": "arm64", - } - - githubOSTypeMap map[string]string = map[string]string{ - "linux": "linux", - "windows": "win", - } - - // - githubOSTag = map[params.OSType]string{ - params.Linux: "Linux", - params.Windows: "Windows", - } -) - -// ResolveToGithubArch returns the cpu architecture as it is defined in the GitHub -// tools download list. We use it to find the proper tools for the OS/Arch combo we're -// deploying. -func ResolveToGithubArch(arch string) (string, error) { - ghArch, ok := githubArchMapping[arch] - if !ok { - return "", runnerErrors.NewNotFoundError("arch %s is unknown", arch) - } - - return ghArch, nil -} - -// ResolveToGithubArch returns the OS type as it is defined in the GitHub -// tools download list. We use it to find the proper tools for the OS/Arch combo we're -// deploying. -func ResolveToGithubOSType(osType string) (string, error) { - ghOS, ok := githubOSTypeMap[osType] - if !ok { - return "", runnerErrors.NewNotFoundError("os %s is unknown", osType) - } - - return ghOS, nil -} - -// ResolveToGithubTag returns the default OS tag that self hosted runners automatically -// (and forcefully) adds to every runner that gets deployed. We need to keep track of those -// tags internally as well. -func ResolveToGithubTag(os params.OSType) (string, error) { - ghOS, ok := githubOSTag[os] - if !ok { - return "", runnerErrors.NewNotFoundError("os %s is unknown", os) - } - - return ghOS, nil -} - -// IsValidEmail returs a bool indicating if an email is valid -func IsValidEmail(email string) bool { - if len(email) > 254 || !rxEmail.MatchString(email) { - return false - } - return true -} - -func IsAlphanumeric(s string) bool { - for _, r := range s { - if !unicode.IsLetter(r) && !unicode.IsNumber(r) { - return false - } - } - return true -} - -// GetLoggingWriter returns a new io.Writer suitable for logging. -func GetLoggingWriter(cfg *config.Config) (io.Writer, error) { - var writer io.Writer = os.Stdout - if cfg.Default.LogFile != "" { - dirname := path.Dir(cfg.Default.LogFile) - if _, err := os.Stat(dirname); err != nil { - if !os.IsNotExist(err) { - return nil, fmt.Errorf("failed to create log folder") - } - if err := os.MkdirAll(dirname, 0o711); err != nil { - return nil, fmt.Errorf("failed to create log folder") - } - } - writer = &lumberjack.Logger{ - Filename: cfg.Default.LogFile, - MaxSize: 500, // megabytes - MaxBackups: 3, - MaxAge: 28, // days - Compress: true, // disabled by default - } - } - return writer, nil -} - -func ConvertFileToBase64(file string) (string, error) { - bytes, err := os.ReadFile(file) - if err != nil { - return "", errors.Wrap(err, "reading file") - } - - return base64.StdEncoding.EncodeToString(bytes), nil -} - -func OSToOSType(os string) (params.OSType, error) { - osType, ok := OSToOSTypeMap[strings.ToLower(os)] - if !ok { - return params.Unknown, fmt.Errorf("no OS to OS type mapping for %s", os) - } - return osType, nil -} - func GithubClient(ctx context.Context, token string, credsDetails params.GithubCredentials) (common.GithubClient, common.GithubEnterpriseClient, error) { var roots *x509.CertPool if credsDetails.CABundle != nil && len(credsDetails.CABundle) > 0 { @@ -224,274 +58,3 @@ func GithubClient(ctx context.Context, token string, credsDetails params.GithubC return ghClient.Actions, ghClient.Enterprise, nil } - -func GetCloudConfig(bootstrapParams params.BootstrapInstance, tools github.RunnerApplicationDownload, runnerName string) (string, error) { - if tools.Filename == nil { - return "", fmt.Errorf("missing tools filename") - } - - if tools.DownloadURL == nil { - return "", fmt.Errorf("missing tools download URL") - } - - var tempToken string - if tools.TempDownloadToken != nil { - tempToken = *tools.TempDownloadToken - } - - installRunnerParams := cloudconfig.InstallRunnerParams{ - FileName: *tools.Filename, - DownloadURL: *tools.DownloadURL, - TempDownloadToken: tempToken, - MetadataURL: bootstrapParams.MetadataURL, - RunnerUsername: appdefaults.DefaultUser, - RunnerGroup: appdefaults.DefaultUser, - RepoURL: bootstrapParams.RepoURL, - RunnerName: runnerName, - RunnerLabels: strings.Join(bootstrapParams.Labels, ","), - CallbackURL: bootstrapParams.CallbackURL, - CallbackToken: bootstrapParams.InstanceToken, - GitHubRunnerGroup: bootstrapParams.GitHubRunnerGroup, - } - if bootstrapParams.CACertBundle != nil && len(bootstrapParams.CACertBundle) > 0 { - installRunnerParams.CABundle = string(bootstrapParams.CACertBundle) - } - - installScript, err := cloudconfig.InstallRunnerScript(installRunnerParams, bootstrapParams.OSType) - if err != nil { - return "", errors.Wrap(err, "generating script") - } - - var asStr string - switch bootstrapParams.OSType { - case params.Linux: - cloudCfg := cloudconfig.NewDefaultCloudInitConfig() - - if bootstrapParams.UserDataOptions.DisableUpdatesOnBoot { - cloudCfg.PackageUpgrade = false - cloudCfg.Packages = []string{} - } - for _, pkg := range bootstrapParams.UserDataOptions.ExtraPackages { - cloudCfg.AddPackage(pkg) - } - - cloudCfg.AddSSHKey(bootstrapParams.SSHKeys...) - cloudCfg.AddFile(installScript, "/install_runner.sh", "root:root", "755") - cloudCfg.AddRunCmd(fmt.Sprintf("su -l -c /install_runner.sh %s", appdefaults.DefaultUser)) - cloudCfg.AddRunCmd("rm -f /install_runner.sh") - if bootstrapParams.CACertBundle != nil && len(bootstrapParams.CACertBundle) > 0 { - if err := cloudCfg.AddCACert(bootstrapParams.CACertBundle); err != nil { - return "", errors.Wrap(err, "adding CA cert bundle") - } - } - var err error - asStr, err = cloudCfg.Serialize() - if err != nil { - return "", errors.Wrap(err, "creating cloud config") - } - case params.Windows: - asStr = string(installScript) - default: - return "", fmt.Errorf("unknown os type: %s", bootstrapParams.OSType) - } - - return asStr, nil -} - -func GetTools(osType params.OSType, osArch params.OSArch, tools []*github.RunnerApplicationDownload) (github.RunnerApplicationDownload, error) { - // Validate image OS. Linux only for now. - switch osType { - case params.Linux: - case params.Windows: - default: - return github.RunnerApplicationDownload{}, fmt.Errorf("unsupported OS type: %s", osType) - } - - switch osArch { - case params.Amd64: - case params.Arm: - case params.Arm64: - default: - return github.RunnerApplicationDownload{}, fmt.Errorf("unsupported OS arch: %s", osArch) - } - - // Find tools for OS/Arch. - for _, tool := range tools { - if tool == nil { - continue - } - if tool.OS == nil || tool.Architecture == nil { - continue - } - - ghArch, err := ResolveToGithubArch(string(osArch)) - if err != nil { - continue - } - - ghOS, err := ResolveToGithubOSType(string(osType)) - if err != nil { - continue - } - if *tool.Architecture == ghArch && *tool.OS == ghOS { - return *tool, nil - } - } - return github.RunnerApplicationDownload{}, fmt.Errorf("failed to find tools for OS %s and arch %s", osType, osArch) -} - -// GetRandomString returns a secure random string -func GetRandomString(n int) (string, error) { - data := make([]byte, n) - _, err := rand.Read(data) - if err != nil { - return "", errors.Wrap(err, "getting random data") - } - for i, b := range data { - data[i] = alphanumeric[b%byte(len(alphanumeric))] - } - - return string(data), nil -} - -func Aes256EncodeString(target string, passphrase string) ([]byte, error) { - if len(passphrase) != 32 { - return nil, fmt.Errorf("invalid passphrase length (expected length 32 characters)") - } - - toEncrypt := []byte(target) - block, err := aes.NewCipher([]byte(passphrase)) - if err != nil { - return nil, errors.Wrap(err, "creating cipher") - } - - aesgcm, err := cipher.NewGCM(block) - if err != nil { - return nil, errors.Wrap(err, "creating new aead") - } - - nonce := make([]byte, aesgcm.NonceSize()) - if _, err := io.ReadFull(rand.Reader, nonce); err != nil { - return nil, errors.Wrap(err, "creating nonce") - } - - ciphertext := aesgcm.Seal(nonce, nonce, toEncrypt, nil) - return ciphertext, nil -} - -func Aes256DecodeString(target []byte, passphrase string) (string, error) { - if len(passphrase) != 32 { - return "", fmt.Errorf("invalid passphrase length (expected length 32 characters)") - } - - block, err := aes.NewCipher([]byte(passphrase)) - if err != nil { - return "", errors.Wrap(err, "creating cipher") - } - - aesgcm, err := cipher.NewGCM(block) - if err != nil { - return "", errors.Wrap(err, "creating new aead") - } - - nonceSize := aesgcm.NonceSize() - if len(target) < nonceSize { - return "", fmt.Errorf("failed to decrypt text") - } - - nonce, ciphertext := target[:nonceSize], target[nonceSize:] - plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil) - if err != nil { - return "", fmt.Errorf("failed to decrypt text") - } - return string(plaintext), nil -} - -// PaswsordToBcrypt returns a bcrypt hash of the specified password using the default cost -func PaswsordToBcrypt(password string) (string, error) { - hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) - if err != nil { - return "", fmt.Errorf("failed to hash password") - } - return string(hashedPassword), nil -} - -func NewLoggingMiddleware(writer io.Writer) func(http.Handler) http.Handler { - return func(next http.Handler) http.Handler { - return gorillaHandlers.CombinedLoggingHandler(writer, next) - } -} - -func SanitizeLogEntry(entry string) string { - return strings.Replace(strings.Replace(entry, "\n", "", -1), "\r", "", -1) -} - -func toBase62(uuid []byte) string { - var i big.Int - i.SetBytes(uuid[:]) - return i.Text(62) -} - -func NewID() string { - short, err := shortid.Generate() - if err == nil { - return toBase62([]byte(short)) - } - newUUID := uuid.New() - return toBase62(newUUID[:]) -} - -func UTF16FromString(s string) ([]uint16, error) { - buf := make([]uint16, 0, len(s)*2+1) - for _, r := range s { - buf = utf16.AppendRune(buf, r) - } - return utf16.AppendRune(buf, '\x00'), nil -} - -func UTF16ToString(s []uint16) string { - for i, v := range s { - if v == 0 { - s = s[0:i] - break - } - } - return string(utf16.Decode(s)) -} - -func Uint16ToByteArray(u []uint16) []byte { - ret := make([]byte, (len(u)-1)*2) - for i := 0; i < len(u)-1; i++ { - binary.LittleEndian.PutUint16(ret[i*2:], uint16(u[i])) - } - return ret -} - -func UTF16EncodedByteArrayFromString(s string) ([]byte, error) { - asUint16, err := UTF16FromString(s) - if err != nil { - return nil, fmt.Errorf("failed to encode to uint16: %w", err) - } - asBytes := Uint16ToByteArray(asUint16) - return asBytes, nil -} - -func CompressData(data []byte) ([]byte, error) { - var b bytes.Buffer - gz := gzip.NewWriter(&b) - - _, err := gz.Write(data) - if err != nil { - return nil, fmt.Errorf("failed to compress data: %w", err) - } - - if err = gz.Flush(); err != nil { - return nil, fmt.Errorf("failed to flush buffer: %w", err) - } - - if err = gz.Close(); err != nil { - return nil, fmt.Errorf("failed to close buffer: %w", err) - } - - return b.Bytes(), nil -} diff --git a/cloudconfig/cloudconfig.go b/vendor/github.com/cloudbase/garm-provider-common/cloudconfig/cloudconfig.go similarity index 94% rename from cloudconfig/cloudconfig.go rename to vendor/github.com/cloudbase/garm-provider-common/cloudconfig/cloudconfig.go index 04296302..fe468ec6 100644 --- a/cloudconfig/cloudconfig.go +++ b/vendor/github.com/cloudbase/garm-provider-common/cloudconfig/cloudconfig.go @@ -21,7 +21,7 @@ import ( "strings" "sync" - "github.com/cloudbase/garm/util/appdefaults" + "github.com/cloudbase/garm-provider-common/defaults" "github.com/pkg/errors" "gopkg.in/yaml.v3" @@ -36,10 +36,10 @@ func NewDefaultCloudInitConfig() *CloudInit { }, SystemInfo: &SystemInfo{ DefaultUser: DefaultUser{ - Name: appdefaults.DefaultUser, - Home: fmt.Sprintf("/home/%s", appdefaults.DefaultUser), - Shell: appdefaults.DefaultUserShell, - Groups: appdefaults.DefaultUserGroups, + Name: defaults.DefaultUser, + Home: fmt.Sprintf("/home/%s", defaults.DefaultUser), + Shell: defaults.DefaultUserShell, + Groups: defaults.DefaultUserGroups, Sudo: "ALL=(ALL) NOPASSWD:ALL", }, }, diff --git a/cloudconfig/templates.go b/vendor/github.com/cloudbase/garm-provider-common/cloudconfig/templates.go similarity index 81% rename from cloudconfig/templates.go rename to vendor/github.com/cloudbase/garm-provider-common/cloudconfig/templates.go index e02c9c77..b27f5cb8 100644 --- a/cloudconfig/templates.go +++ b/vendor/github.com/cloudbase/garm-provider-common/cloudconfig/templates.go @@ -19,7 +19,7 @@ import ( "fmt" "text/template" - "github.com/cloudbase/garm/params" + "github.com/cloudbase/garm-provider-common/params" "github.com/pkg/errors" ) @@ -28,6 +28,10 @@ var CloudConfigTemplate = `#!/bin/bash set -e set -o pipefail +{{- if .EnableBootDebug }} +set -x +{{- end }} + CALLBACK_URL="{{ .CallbackURL }}" METADATA_URL="{{ .MetadataURL }}" BEARER_TOKEN="{{ .CallbackToken }}" @@ -40,6 +44,10 @@ GITHUB_TOKEN=$(curl --retry 5 --retry-delay 5 --retry-connrefused --fail -s -X G function call() { PAYLOAD="$1" + [[ $CALLBACK_URL =~ ^(.*)/status$ ]] + if [ -z "$BASH_REMATCH" ];then + CALLBACK_URL="${CALLBACK_URL}/status" + fi curl --retry 5 --retry-delay 5 --retry-connrefused --fail -s -X POST -d "${PAYLOAD}" -H 'Accept: application/json' -H "Authorization: Bearer ${BEARER_TOKEN}" "${CALLBACK_URL}" || echo "failed to call home: exit code ($?)" } @@ -350,6 +358,10 @@ $GHRunnerGroup = "{{.GitHubRunnerGroup}}" function Install-Runner() { $CallbackURL="{{.CallbackURL}}" + if (!$CallbackURL.EndsWith("/status")) { + $CallbackURL = "$CallbackURL/status" + } + if ($Token.Length -eq 0) { Throw "missing callback authentication token" } @@ -402,31 +414,59 @@ function Install-Runner() { Install-Runner ` +// InstallRunnerParams holds the parameters needed to render the runner install script. type InstallRunnerParams struct { - FileName string - DownloadURL string - RunnerUsername string - RunnerGroup string - RepoURL string - MetadataURL string - RunnerName string - RunnerLabels string - CallbackURL string - CallbackToken string + // FileName is the name of the file that will be downloaded from the download URL. + // This will be the runner archive downloaded from GitHub. + FileName string + // DownloadURL is the URL from which the runner archive will be downloaded. + DownloadURL string + // RunnerUsername is the username of the user that will run the runner service. + RunnerUsername string + // RunnerGroup is the group of the user that will run the runner service. + RunnerGroup string + // RepoURL is the URL or the github repo the github runner agent needs to configure itself. + RepoURL string + // MetadataURL is the URL where instances can fetch information needed to set themselves up. + // This URL is set in the GARM config file. + MetadataURL string + // RunnerName is the name of the runner. GARM will use this to register the runner with GitHub. + RunnerName string + // RunnerLabels is a comma separated list of labels that will be added to the runner. + RunnerLabels string + // CallbackURL is the URL where the instance can send a post, signaling progress or status. + // This URL is set in the GARM config file. + CallbackURL string + // CallbackToken is the token that needs to be set by the instance in the headers in order to call + // the CallbackURL. + CallbackToken string + // TempDownloadToken is the token that needs to be set by the instance in the headers in order to download + // the githun runner. This is usually needed when using garm against a GHES instance. TempDownloadToken string - CABundle string + // CABundle is a CA certificate bundle which will be sent to instances and which will tipically be installed + // as a system wide trusted root CA by either cloud-init or whatever mechanism the provider will use to set + // up the runner. + CABundle string + // GitHubRunnerGroup is the github runner group in which the newly installed runner should be added to. GitHubRunnerGroup string + // EnableBootDebug will enable bash debug mode. + EnableBootDebug bool + // ExtraContext is a map of extra context that will be passed to the runner install template. + // This option is useful for situations in which you're supplying your own template and you need + // to pass in information that is not available in the default template. + ExtraContext map[string]string } -func InstallRunnerScript(installParams InstallRunnerParams, osType params.OSType) ([]byte, error) { - var tpl string - switch osType { - case params.Linux: - tpl = CloudConfigTemplate - case params.Windows: - tpl = WindowsSetupScriptTemplate - default: - return nil, fmt.Errorf("unsupported os type: %s", osType) +func InstallRunnerScript(installParams InstallRunnerParams, osType params.OSType, tpl string) ([]byte, error) { + if tpl == "" { + switch osType { + case params.Linux: + tpl = CloudConfigTemplate + case params.Windows: + tpl = WindowsSetupScriptTemplate + default: + return nil, fmt.Errorf("unsupported os type: %s", osType) + } } t, err := template.New("").Parse(tpl) diff --git a/vendor/github.com/cloudbase/garm-provider-common/cloudconfig/util.go b/vendor/github.com/cloudbase/garm-provider-common/cloudconfig/util.go new file mode 100644 index 00000000..d9a69a16 --- /dev/null +++ b/vendor/github.com/cloudbase/garm-provider-common/cloudconfig/util.go @@ -0,0 +1,197 @@ +package cloudconfig + +import ( + "encoding/json" + "fmt" + "sort" + "strings" + + "github.com/cloudbase/garm-provider-common/defaults" + commonParams "github.com/cloudbase/garm-provider-common/params" + "github.com/google/go-github/v53/github" + "github.com/pkg/errors" +) + +// CloudConfigSpec is a struct that holds extra specs that can be used to customize user data. +type CloudConfigSpec struct { + // RunnerInstallTemplate can be used to override the default runner install template. + // If used, the caller is responsible for the correctness of the template as well as the + // suitability of the template for the target OS. + RunnerInstallTemplate []byte `json:"runner_install_template"` + // PreInstallScripts is a map of pre-install scripts that will be run before the + // runner install script. These will run as root and can be used to prep a generic image + // before we attempt to install the runner. The key of the map is the name of the script + // as it will be written to disk. The value is a byte array with the contents of the script. + // + // These scripts will be added and run in alphabetical order. + // + // On Linux, we will set the executable flag. On Windows, the name matters as Windows looks for an + // extension to determine if the file is an executable or not. In theory this can hold binaries, + // but in most cases this will most likely hold scripts. We do not currenly validate the payload, + // so it's up to the user what they upload here. + // Caution needs to be exercised when using this feature, as the total size of userdata is limited + // on most providers. + PreInstallScripts map[string][]byte `json:"pre_install_scripts"` + // ExtraContext is a map of extra context that will be passed to the runner install template. + ExtraContext map[string]string `json:"extra_context"` +} + +func sortMapKeys(m map[string][]byte) []string { + var keys []string + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + + return keys +} + +// GetSpecs returns the cloud config specific extra specs from the bootstrap params. +func GetSpecs(bootstrapParams commonParams.BootstrapInstance) (CloudConfigSpec, error) { + var extraSpecs CloudConfigSpec + if len(bootstrapParams.ExtraSpecs) == 0 { + return extraSpecs, nil + } + + if err := json.Unmarshal(bootstrapParams.ExtraSpecs, &extraSpecs); err != nil { + return CloudConfigSpec{}, errors.Wrap(err, "unmarshaling extra specs") + } + + if extraSpecs.ExtraContext == nil { + extraSpecs.ExtraContext = map[string]string{} + } + + if extraSpecs.PreInstallScripts == nil { + extraSpecs.PreInstallScripts = map[string][]byte{} + } + + return extraSpecs, nil +} + +// GetRunnerInstallScript returns the runner install script for the given bootstrap params. +// This function will return either the default script for the given OS type or will use the supplied template +// if one is provided. +func GetRunnerInstallScript(bootstrapParams commonParams.BootstrapInstance, tools github.RunnerApplicationDownload, runnerName string) ([]byte, error) { + if tools.Filename == nil { + return nil, fmt.Errorf("missing tools filename") + } + + if tools.DownloadURL == nil { + return nil, fmt.Errorf("missing tools download URL") + } + + var tempToken string + if tools.TempDownloadToken != nil { + tempToken = *tools.TempDownloadToken + } + + extraSpecs, err := GetSpecs(bootstrapParams) + if err != nil { + return nil, errors.Wrap(err, "getting specs") + } + + installRunnerParams := InstallRunnerParams{ + FileName: *tools.Filename, + DownloadURL: *tools.DownloadURL, + TempDownloadToken: tempToken, + MetadataURL: bootstrapParams.MetadataURL, + RunnerUsername: defaults.DefaultUser, + RunnerGroup: defaults.DefaultUser, + RepoURL: bootstrapParams.RepoURL, + RunnerName: runnerName, + RunnerLabels: strings.Join(bootstrapParams.Labels, ","), + CallbackURL: bootstrapParams.CallbackURL, + CallbackToken: bootstrapParams.InstanceToken, + GitHubRunnerGroup: bootstrapParams.GitHubRunnerGroup, + ExtraContext: extraSpecs.ExtraContext, + EnableBootDebug: bootstrapParams.UserDataOptions.EnableBootDebug, + } + + if bootstrapParams.CACertBundle != nil && len(bootstrapParams.CACertBundle) > 0 { + installRunnerParams.CABundle = string(bootstrapParams.CACertBundle) + } + + installScript, err := InstallRunnerScript(installRunnerParams, bootstrapParams.OSType, string(extraSpecs.RunnerInstallTemplate)) + if err != nil { + return nil, errors.Wrap(err, "generating script") + } + + return installScript, nil +} + +// GetCloudInitConfig returns the cloud-init specific userdata config. This config can be used on most clouds +// for most Linux machines. The install runner script must be generated separately either by GetRunnerInstallScript() +// or some other means. +func GetCloudInitConfig(bootstrapParams commonParams.BootstrapInstance, installScript []byte) (string, error) { + extraSpecs, err := GetSpecs(bootstrapParams) + if err != nil { + return "", errors.Wrap(err, "getting specs") + } + + cloudCfg := NewDefaultCloudInitConfig() + + if bootstrapParams.UserDataOptions.DisableUpdatesOnBoot { + cloudCfg.PackageUpgrade = false + cloudCfg.Packages = []string{} + } + for _, pkg := range bootstrapParams.UserDataOptions.ExtraPackages { + cloudCfg.AddPackage(pkg) + } + + if len(extraSpecs.PreInstallScripts) > 0 { + names := sortMapKeys(extraSpecs.PreInstallScripts) + for _, name := range names { + script := extraSpecs.PreInstallScripts[name] + cloudCfg.AddFile(script, fmt.Sprintf("/garm-pre-install/%s", name), "root:root", "755") + cloudCfg.AddRunCmd(fmt.Sprintf("/garm-pre-install/%s", name)) + } + } + cloudCfg.AddRunCmd("rm -rf /garm-pre-install") + + cloudCfg.AddSSHKey(bootstrapParams.SSHKeys...) + cloudCfg.AddFile(installScript, "/install_runner.sh", "root:root", "755") + cloudCfg.AddRunCmd(fmt.Sprintf("su -l -c /install_runner.sh %s", defaults.DefaultUser)) + cloudCfg.AddRunCmd("rm -f /install_runner.sh") + if bootstrapParams.CACertBundle != nil && len(bootstrapParams.CACertBundle) > 0 { + if err := cloudCfg.AddCACert(bootstrapParams.CACertBundle); err != nil { + return "", errors.Wrap(err, "adding CA cert bundle") + } + } + + asStr, err := cloudCfg.Serialize() + if err != nil { + return "", errors.Wrap(err, "creating cloud config") + } + + return asStr, nil +} + +// GetCloudConfig is a helper function that generates a cloud-init config for Linux and a powershell script for Windows. +// In most cases this function should do, but in situations where a more custom approach is needed, you may need to call +// GetCloudInitConfig() or GetRunnerInstallScript() directly and compose the final userdata in a different way. +// The extra specs PreInstallScripts is only supported on Linux via cloud-init by this function. On some providers, like Azure +// Windows initialization scripts are run by creating a separate CustomScriptExtension resource for each individual script. +// On other clouds it may be different. This function aims to be generic, which is why it only supports the PreInstallScripts +// via cloud-init. +func GetCloudConfig(bootstrapParams commonParams.BootstrapInstance, tools github.RunnerApplicationDownload, runnerName string) (string, error) { + installScript, err := GetRunnerInstallScript(bootstrapParams, tools, runnerName) + if err != nil { + return "", errors.Wrap(err, "generating script") + } + + var asStr string + switch bootstrapParams.OSType { + case commonParams.Linux: + cloudCfg, err := GetCloudInitConfig(bootstrapParams, installScript) + if err != nil { + return "", errors.Wrap(err, "getting cloud init config") + } + return cloudCfg, nil + case commonParams.Windows: + asStr = string(installScript) + default: + return "", fmt.Errorf("unknown os type: %s", bootstrapParams.OSType) + } + + return asStr, nil +} diff --git a/vendor/github.com/cloudbase/garm-provider-common/defaults/defaults.go b/vendor/github.com/cloudbase/garm-provider-common/defaults/defaults.go new file mode 100644 index 00000000..e461d10a --- /dev/null +++ b/vendor/github.com/cloudbase/garm-provider-common/defaults/defaults.go @@ -0,0 +1,17 @@ +package defaults + +const ( + // DefaultUser is the default username that should exist on the instances. + DefaultUser = "runner" + // DefaultUserShell is the shell for the default user. + DefaultUserShell = "/bin/bash" +) + +var ( + // DefaultUserGroups are the groups the default user will be part of. + DefaultUserGroups = []string{ + "sudo", "adm", "cdrom", "dialout", + "dip", "video", "plugdev", "netdev", + "docker", "lxd", + } +) diff --git a/errors/errors.go b/vendor/github.com/cloudbase/garm-provider-common/errors/errors.go similarity index 100% rename from errors/errors.go rename to vendor/github.com/cloudbase/garm-provider-common/errors/errors.go diff --git a/runner/providers/external/execution/commands.go b/vendor/github.com/cloudbase/garm-provider-common/execution/commands.go similarity index 100% rename from runner/providers/external/execution/commands.go rename to vendor/github.com/cloudbase/garm-provider-common/execution/commands.go diff --git a/runner/providers/external/execution/execution.go b/vendor/github.com/cloudbase/garm-provider-common/execution/execution.go similarity index 89% rename from runner/providers/external/execution/execution.go rename to vendor/github.com/cloudbase/garm-provider-common/execution/execution.go index 19fb9109..448ea84e 100644 --- a/runner/providers/external/execution/execution.go +++ b/vendor/github.com/cloudbase/garm-provider-common/execution/execution.go @@ -4,15 +4,36 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "os" - "github.com/cloudbase/garm/params" + gErrors "github.com/cloudbase/garm-provider-common/errors" + "github.com/cloudbase/garm-provider-common/params" "github.com/mattn/go-isatty" ) +const ( + // ExitCodeNotFound is an exit code that indicates a Not Found error + ExitCodeNotFound int = 30 + // ExitCodeDuplicate is an exit code that indicates a duplicate error + ExitCodeDuplicate int = 31 +) + +func ResolveErrorToExitCode(err error) int { + if err != nil { + if errors.Is(err, gErrors.ErrNotFound) { + return ExitCodeNotFound + } else if errors.Is(err, gErrors.ErrDuplicateEntity) { + return ExitCodeDuplicate + } + return 1 + } + return 0 +} + func GetEnvironment() (Environment, error) { env := Environment{ Command: ExecutionCommand(os.Getenv("GARM_COMMAND")), diff --git a/runner/providers/external/execution/interface.go b/vendor/github.com/cloudbase/garm-provider-common/execution/interface.go similarity index 78% rename from runner/providers/external/execution/interface.go rename to vendor/github.com/cloudbase/garm-provider-common/execution/interface.go index 7c8cc90f..20188368 100644 --- a/runner/providers/external/execution/interface.go +++ b/vendor/github.com/cloudbase/garm-provider-common/execution/interface.go @@ -3,7 +3,7 @@ package execution import ( "context" - "github.com/cloudbase/garm/params" + "github.com/cloudbase/garm-provider-common/params" ) // ExternalProvider defines an interface that external providers need to implement. @@ -11,13 +11,13 @@ import ( // decouple it, in case it may diverge from native providers. type ExternalProvider interface { // CreateInstance creates a new compute instance in the provider. - CreateInstance(ctx context.Context, bootstrapParams params.BootstrapInstance) (params.Instance, error) + CreateInstance(ctx context.Context, bootstrapParams params.BootstrapInstance) (params.ProviderInstance, error) // Delete instance will delete the instance in a provider. DeleteInstance(ctx context.Context, instance string) error // GetInstance will return details about one instance. - GetInstance(ctx context.Context, instance string) (params.Instance, error) + GetInstance(ctx context.Context, instance string) (params.ProviderInstance, error) // ListInstances will list all instances for a provider. - ListInstances(ctx context.Context, poolID string) ([]params.Instance, error) + ListInstances(ctx context.Context, poolID string) ([]params.ProviderInstance, error) // RemoveAllInstances will remove all instances created by this provider. RemoveAllInstances(ctx context.Context) error // Stop shuts down the instance. diff --git a/vendor/github.com/cloudbase/garm-provider-common/params/params.go b/vendor/github.com/cloudbase/garm-provider-common/params/params.go new file mode 100644 index 00000000..ccee9859 --- /dev/null +++ b/vendor/github.com/cloudbase/garm-provider-common/params/params.go @@ -0,0 +1,149 @@ +package params + +import ( + "encoding/json" + + "github.com/google/go-github/v53/github" +) + +type ( + AddressType string + InstanceStatus string + OSType string + OSArch string +) + +const ( + Windows OSType = "windows" + Linux OSType = "linux" + Unknown OSType = "unknown" +) + +const ( + Amd64 OSArch = "amd64" + I386 OSArch = "i386" + Arm64 OSArch = "arm64" + Arm OSArch = "arm" +) + +const ( + InstanceRunning InstanceStatus = "running" + InstanceStopped InstanceStatus = "stopped" + InstanceError InstanceStatus = "error" + InstancePendingDelete InstanceStatus = "pending_delete" + InstanceDeleting InstanceStatus = "deleting" + InstancePendingCreate InstanceStatus = "pending_create" + InstanceCreating InstanceStatus = "creating" + InstanceStatusUnknown InstanceStatus = "unknown" +) + +const ( + PublicAddress AddressType = "public" + PrivateAddress AddressType = "private" +) + +type UserDataOptions struct { + DisableUpdatesOnBoot bool `json:"disable_updates_on_boot"` + ExtraPackages []string `json:"extra_packages"` + EnableBootDebug bool `json:"enable_boot_debug"` +} + +type BootstrapInstance struct { + Name string `json:"name"` + Tools []*github.RunnerApplicationDownload `json:"tools"` + // RepoURL is the URL the github runner agent needs to configure itself. + RepoURL string `json:"repo_url"` + // CallbackUrl is the URL where the instance can send a post, signaling + // progress or status. + CallbackURL string `json:"callback-url"` + // MetadataURL is the URL where instances can fetch information needed to set themselves up. + MetadataURL string `json:"metadata-url"` + // InstanceToken is the token that needs to be set by the instance in the headers + // in order to send updated back to the garm via CallbackURL. + InstanceToken string `json:"instance-token"` + // SSHKeys are the ssh public keys we may want to inject inside the runners, if the + // provider supports it. + SSHKeys []string `json:"ssh-keys"` + // ExtraSpecs is an opaque raw json that gets sent to the provider + // as part of the bootstrap params for instances. It can contain + // any kind of data needed by providers. The contents of this field means + // nothing to garm itself. We don't act on the information in this field at + // all. We only validate that it's a proper json. + ExtraSpecs json.RawMessage `json:"extra_specs,omitempty"` + + // GitHubRunnerGroup is the github runner group in which the newly installed runner + // should be added to. The runner group must be created by someone with access to the + // enterprise. + GitHubRunnerGroup string `json:"github-runner-group"` + + // CACertBundle is a CA certificate bundle which will be sent to instances and which + // will tipically be installed as a system wide trusted root CA. by either cloud-init + // or whatever mechanism the provider will use to set up the runner. + CACertBundle []byte `json:"ca-cert-bundle"` + + // OSArch is the target OS CPU architecture of the runner. + OSArch OSArch `json:"arch"` + + // OSType is the target OS platform of the runner (windows, linux). + OSType OSType `json:"os_type"` + + // Flavor is the platform specific abstraction that defines what resources will be allocated + // to the runner (CPU, RAM, disk space, etc). This field is meaningful to the provider which + // handles the actual creation. + Flavor string `json:"flavor"` + + // Image is the platform specific identifier of the operating system template that will be used + // to spin up a new machine. + Image string `json:"image"` + + // Labels are a list of github runner labels that will be added to the runner. + Labels []string `json:"labels"` + + // PoolID is the ID of the garm pool to which this runner belongs. + PoolID string `json:"pool_id"` + + // UserDataOptions are the options for the user data generation. + UserDataOptions UserDataOptions `json:"user_data_options"` +} + +type Address struct { + Address string `json:"address"` + Type AddressType `json:"type"` +} + +type ProviderInstance struct { + // PeoviderID is the unique ID the provider associated + // with the compute instance. We use this to identify the + // instance in the provider. + ProviderID string `json:"provider_id,omitempty"` + + // Name is the name associated with an instance. Depending on + // the provider, this may or may not be useful in the context of + // the provider, but we can use it internally to identify the + // instance. + Name string `json:"name,omitempty"` + + // OSType is the operating system type. For now, only Linux and + // Windows are supported. + OSType OSType `json:"os_type,omitempty"` + + // OSName is the name of the OS. Eg: ubuntu, centos, etc. + OSName string `json:"os_name,omitempty"` + + // OSVersion is the version of the operating system. + OSVersion string `json:"os_version,omitempty"` + + // OSArch is the operating system architecture. + OSArch OSArch `json:"os_arch,omitempty"` + + // Addresses is a list of IP addresses the provider reports + // for this instance. + Addresses []Address `json:"addresses,omitempty"` + + // Status is the status of the instance inside the provider (eg: running, stopped, etc) + Status InstanceStatus `json:"status,omitempty"` + + // ProviderFault holds any error messages captured from the IaaS provider that is + // responsible for managing the lifecycle of the runner. + ProviderFault []byte `json:"provider_fault,omitempty"` +} diff --git a/util/exec/exec.go b/vendor/github.com/cloudbase/garm-provider-common/util/exec/exec.go similarity index 100% rename from util/exec/exec.go rename to vendor/github.com/cloudbase/garm-provider-common/util/exec/exec.go diff --git a/util/exec/exec_nix.go b/vendor/github.com/cloudbase/garm-provider-common/util/exec/exec_nix.go similarity index 100% rename from util/exec/exec_nix.go rename to vendor/github.com/cloudbase/garm-provider-common/util/exec/exec_nix.go diff --git a/util/exec/exec_windows.go b/vendor/github.com/cloudbase/garm-provider-common/util/exec/exec_windows.go similarity index 100% rename from util/exec/exec_windows.go rename to vendor/github.com/cloudbase/garm-provider-common/util/exec/exec_windows.go diff --git a/vendor/github.com/cloudbase/garm-provider-common/util/util.go b/vendor/github.com/cloudbase/garm-provider-common/util/util.go new file mode 100644 index 00000000..1f9e9415 --- /dev/null +++ b/vendor/github.com/cloudbase/garm-provider-common/util/util.go @@ -0,0 +1,387 @@ +// Copyright 2023 Cloudbase Solutions SRL +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. + +package util + +import ( + "bytes" + "compress/gzip" + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "encoding/base64" + "encoding/binary" + "fmt" + "io" + "math/big" + "net/http" + "os" + "path" + "regexp" + "strings" + "unicode" + "unicode/utf16" + + runnerErrors "github.com/cloudbase/garm-provider-common/errors" + + commonParams "github.com/cloudbase/garm-provider-common/params" + + "github.com/google/go-github/v53/github" + "github.com/google/uuid" + gorillaHandlers "github.com/gorilla/handlers" + "github.com/pkg/errors" + "github.com/teris-io/shortid" + "golang.org/x/crypto/bcrypt" + lumberjack "gopkg.in/natefinch/lumberjack.v2" +) + +const alphanumeric = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + +// From: https://www.alexedwards.net/blog/validation-snippets-for-go#email-validation +var rxEmail = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") + +var ( + OSToOSTypeMap map[string]commonParams.OSType = map[string]commonParams.OSType{ + "almalinux": commonParams.Linux, + "alma": commonParams.Linux, + "alpine": commonParams.Linux, + "archlinux": commonParams.Linux, + "arch": commonParams.Linux, + "centos": commonParams.Linux, + "ubuntu": commonParams.Linux, + "rhel": commonParams.Linux, + "suse": commonParams.Linux, + "opensuse": commonParams.Linux, + "fedora": commonParams.Linux, + "debian": commonParams.Linux, + "flatcar": commonParams.Linux, + "gentoo": commonParams.Linux, + "rockylinux": commonParams.Linux, + "rocky": commonParams.Linux, + "windows": commonParams.Windows, + } + + githubArchMapping map[string]string = map[string]string{ + "x86_64": "x64", + "amd64": "x64", + "armv7l": "arm", + "aarch64": "arm64", + "x64": "x64", + "arm": "arm", + "arm64": "arm64", + } + + githubOSTypeMap map[string]string = map[string]string{ + "linux": "linux", + "windows": "win", + } + + // + githubOSTag = map[commonParams.OSType]string{ + commonParams.Linux: "Linux", + commonParams.Windows: "Windows", + } +) + +// ResolveToGithubArch returns the cpu architecture as it is defined in the GitHub +// tools download list. We use it to find the proper tools for the OS/Arch combo we're +// deploying. +func ResolveToGithubArch(arch string) (string, error) { + ghArch, ok := githubArchMapping[arch] + if !ok { + return "", runnerErrors.NewNotFoundError("arch %s is unknown", arch) + } + + return ghArch, nil +} + +// ResolveToGithubArch returns the OS type as it is defined in the GitHub +// tools download list. We use it to find the proper tools for the OS/Arch combo we're +// deploying. +func ResolveToGithubOSType(osType string) (string, error) { + ghOS, ok := githubOSTypeMap[osType] + if !ok { + return "", runnerErrors.NewNotFoundError("os %s is unknown", osType) + } + + return ghOS, nil +} + +// ResolveToGithubTag returns the default OS tag that self hosted runners automatically +// (and forcefully) adds to every runner that gets deployed. We need to keep track of those +// tags internally as well. +func ResolveToGithubTag(os commonParams.OSType) (string, error) { + ghOS, ok := githubOSTag[os] + if !ok { + return "", runnerErrors.NewNotFoundError("os %s is unknown", os) + } + + return ghOS, nil +} + +// IsValidEmail returs a bool indicating if an email is valid +func IsValidEmail(email string) bool { + if len(email) > 254 || !rxEmail.MatchString(email) { + return false + } + return true +} + +func IsAlphanumeric(s string) bool { + for _, r := range s { + if !unicode.IsLetter(r) && !unicode.IsNumber(r) { + return false + } + } + return true +} + +// GetLoggingWriter returns a new io.Writer suitable for logging. +func GetLoggingWriter(logFile string) (io.Writer, error) { + var writer io.Writer = os.Stdout + if logFile != "" { + dirname := path.Dir(logFile) + if _, err := os.Stat(dirname); err != nil { + if !os.IsNotExist(err) { + return nil, fmt.Errorf("failed to create log folder") + } + if err := os.MkdirAll(dirname, 0o711); err != nil { + return nil, fmt.Errorf("failed to create log folder") + } + } + writer = &lumberjack.Logger{ + Filename: logFile, + MaxSize: 500, // megabytes + MaxBackups: 3, + MaxAge: 28, // days + Compress: true, // disabled by default + } + } + return writer, nil +} + +func ConvertFileToBase64(file string) (string, error) { + bytes, err := os.ReadFile(file) + if err != nil { + return "", errors.Wrap(err, "reading file") + } + + return base64.StdEncoding.EncodeToString(bytes), nil +} + +func OSToOSType(os string) (commonParams.OSType, error) { + osType, ok := OSToOSTypeMap[strings.ToLower(os)] + if !ok { + return commonParams.Unknown, fmt.Errorf("no OS to OS type mapping for %s", os) + } + return osType, nil +} + +func GetTools(osType commonParams.OSType, osArch commonParams.OSArch, tools []*github.RunnerApplicationDownload) (github.RunnerApplicationDownload, error) { + // Validate image OS. Linux only for now. + switch osType { + case commonParams.Linux: + case commonParams.Windows: + default: + return github.RunnerApplicationDownload{}, fmt.Errorf("unsupported OS type: %s", osType) + } + + switch osArch { + case commonParams.Amd64: + case commonParams.Arm: + case commonParams.Arm64: + default: + return github.RunnerApplicationDownload{}, fmt.Errorf("unsupported OS arch: %s", osArch) + } + + // Find tools for OS/Arch. + for _, tool := range tools { + if tool == nil { + continue + } + if tool.OS == nil || tool.Architecture == nil { + continue + } + + ghArch, err := ResolveToGithubArch(string(osArch)) + if err != nil { + continue + } + + ghOS, err := ResolveToGithubOSType(string(osType)) + if err != nil { + continue + } + if *tool.Architecture == ghArch && *tool.OS == ghOS { + return *tool, nil + } + } + return github.RunnerApplicationDownload{}, fmt.Errorf("failed to find tools for OS %s and arch %s", osType, osArch) +} + +// GetRandomString returns a secure random string +func GetRandomString(n int) (string, error) { + data := make([]byte, n) + _, err := rand.Read(data) + if err != nil { + return "", errors.Wrap(err, "getting random data") + } + for i, b := range data { + data[i] = alphanumeric[b%byte(len(alphanumeric))] + } + + return string(data), nil +} + +func Aes256EncodeString(target string, passphrase string) ([]byte, error) { + if len(passphrase) != 32 { + return nil, fmt.Errorf("invalid passphrase length (expected length 32 characters)") + } + + toEncrypt := []byte(target) + block, err := aes.NewCipher([]byte(passphrase)) + if err != nil { + return nil, errors.Wrap(err, "creating cipher") + } + + aesgcm, err := cipher.NewGCM(block) + if err != nil { + return nil, errors.Wrap(err, "creating new aead") + } + + nonce := make([]byte, aesgcm.NonceSize()) + if _, err := io.ReadFull(rand.Reader, nonce); err != nil { + return nil, errors.Wrap(err, "creating nonce") + } + + ciphertext := aesgcm.Seal(nonce, nonce, toEncrypt, nil) + return ciphertext, nil +} + +func Aes256DecodeString(target []byte, passphrase string) (string, error) { + if len(passphrase) != 32 { + return "", fmt.Errorf("invalid passphrase length (expected length 32 characters)") + } + + block, err := aes.NewCipher([]byte(passphrase)) + if err != nil { + return "", errors.Wrap(err, "creating cipher") + } + + aesgcm, err := cipher.NewGCM(block) + if err != nil { + return "", errors.Wrap(err, "creating new aead") + } + + nonceSize := aesgcm.NonceSize() + if len(target) < nonceSize { + return "", fmt.Errorf("failed to decrypt text") + } + + nonce, ciphertext := target[:nonceSize], target[nonceSize:] + plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil) + if err != nil { + return "", fmt.Errorf("failed to decrypt text") + } + return string(plaintext), nil +} + +// PaswsordToBcrypt returns a bcrypt hash of the specified password using the default cost +func PaswsordToBcrypt(password string) (string, error) { + hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return "", fmt.Errorf("failed to hash password") + } + return string(hashedPassword), nil +} + +func NewLoggingMiddleware(writer io.Writer) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return gorillaHandlers.CombinedLoggingHandler(writer, next) + } +} + +func SanitizeLogEntry(entry string) string { + return strings.Replace(strings.Replace(entry, "\n", "", -1), "\r", "", -1) +} + +func toBase62(uuid []byte) string { + var i big.Int + i.SetBytes(uuid[:]) + return i.Text(62) +} + +func NewID() string { + short, err := shortid.Generate() + if err == nil { + return toBase62([]byte(short)) + } + newUUID := uuid.New() + return toBase62(newUUID[:]) +} + +func UTF16FromString(s string) ([]uint16, error) { + buf := make([]uint16, 0, len(s)*2+1) + for _, r := range s { + buf = utf16.AppendRune(buf, r) + } + return utf16.AppendRune(buf, '\x00'), nil +} + +func UTF16ToString(s []uint16) string { + for i, v := range s { + if v == 0 { + s = s[0:i] + break + } + } + return string(utf16.Decode(s)) +} + +func Uint16ToByteArray(u []uint16) []byte { + ret := make([]byte, (len(u)-1)*2) + for i := 0; i < len(u)-1; i++ { + binary.LittleEndian.PutUint16(ret[i*2:], uint16(u[i])) + } + return ret +} + +func UTF16EncodedByteArrayFromString(s string) ([]byte, error) { + asUint16, err := UTF16FromString(s) + if err != nil { + return nil, fmt.Errorf("failed to encode to uint16: %w", err) + } + asBytes := Uint16ToByteArray(asUint16) + return asBytes, nil +} + +func CompressData(data []byte) ([]byte, error) { + var b bytes.Buffer + gz := gzip.NewWriter(&b) + + _, err := gz.Write(data) + if err != nil { + return nil, fmt.Errorf("failed to compress data: %w", err) + } + + if err = gz.Flush(); err != nil { + return nil, fmt.Errorf("failed to flush buffer: %w", err) + } + + if err = gz.Close(); err != nil { + return nil, fmt.Errorf("failed to close buffer: %w", err) + } + + return b.Bytes(), nil +} diff --git a/vendor/github.com/go-resty/resty/v2/.gitignore b/vendor/github.com/go-resty/resty/v2/.gitignore deleted file mode 100644 index 9e856bd4..00000000 --- a/vendor/github.com/go-resty/resty/v2/.gitignore +++ /dev/null @@ -1,30 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof - -coverage.out -coverage.txt - -# Exclude intellij IDE folders -.idea/* diff --git a/vendor/github.com/go-resty/resty/v2/BUILD.bazel b/vendor/github.com/go-resty/resty/v2/BUILD.bazel deleted file mode 100644 index 03bb44c3..00000000 --- a/vendor/github.com/go-resty/resty/v2/BUILD.bazel +++ /dev/null @@ -1,48 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") -load("@bazel_gazelle//:def.bzl", "gazelle") - -# gazelle:prefix github.com/go-resty/resty/v2 -# gazelle:go_naming_convention import_alias -gazelle(name = "gazelle") - -go_library( - name = "resty", - srcs = [ - "client.go", - "middleware.go", - "redirect.go", - "request.go", - "response.go", - "resty.go", - "retry.go", - "trace.go", - "transport.go", - "transport112.go", - "util.go", - ], - importpath = "github.com/go-resty/resty/v2", - visibility = ["//visibility:public"], - deps = ["@org_golang_x_net//publicsuffix:go_default_library"], -) - -go_test( - name = "resty_test", - srcs = [ - "client_test.go", - "context_test.go", - "example_test.go", - "request_test.go", - "resty_test.go", - "retry_test.go", - "util_test.go", - ], - data = glob([".testdata/*"]), - embed = [":resty"], - deps = ["@org_golang_x_net//proxy:go_default_library"], -) - -alias( - name = "go_default_library", - actual = ":resty", - visibility = ["//visibility:public"], -) diff --git a/vendor/github.com/go-resty/resty/v2/LICENSE b/vendor/github.com/go-resty/resty/v2/LICENSE deleted file mode 100644 index 27326a65..00000000 --- a/vendor/github.com/go-resty/resty/v2/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015-2021 Jeevanandam M., https://myjeeva.com - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/go-resty/resty/v2/README.md b/vendor/github.com/go-resty/resty/v2/README.md deleted file mode 100644 index 8ec65182..00000000 --- a/vendor/github.com/go-resty/resty/v2/README.md +++ /dev/null @@ -1,906 +0,0 @@ -

-

Resty

-

Simple HTTP and REST client library for Go (inspired by Ruby rest-client)

-

Features section describes in detail about Resty capabilities

-

-

-

Build Status Code Coverage Go Report Card Release Version GoDoc License Mentioned in Awesome Go

-

-

-

Resty Communication Channels

-

Chat on Gitter - Resty Community Twitter @go_resty

-

- -## News - - * v2.7.0 [released](https://github.com/go-resty/resty/releases/tag/v2.7.0) and tagged on Nov 03, 2021. - * v2.0.0 [released](https://github.com/go-resty/resty/releases/tag/v2.0.0) and tagged on Jul 16, 2019. - * v1.12.0 [released](https://github.com/go-resty/resty/releases/tag/v1.12.0) and tagged on Feb 27, 2019. - * v1.0 released and tagged on Sep 25, 2017. - Resty's first version was released on Sep 15, 2015 then it grew gradually as a very handy and helpful library. Its been a two years since first release. I'm very thankful to Resty users and its [contributors](https://github.com/go-resty/resty/graphs/contributors). - -## Features - - * GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS, etc. - * Simple and chainable methods for settings and request - * [Request](https://pkg.go.dev/github.com/go-resty/resty/v2#Request) Body can be `string`, `[]byte`, `struct`, `map`, `slice` and `io.Reader` too - * Auto detects `Content-Type` - * Buffer less processing for `io.Reader` - * Native `*http.Request` instance may be accessed during middleware and request execution via `Request.RawRequest` - * Request Body can be read multiple times via `Request.RawRequest.GetBody()` - * [Response](https://pkg.go.dev/github.com/go-resty/resty/v2#Response) object gives you more possibility - * Access as `[]byte` array - `response.Body()` OR Access as `string` - `response.String()` - * Know your `response.Time()` and when we `response.ReceivedAt()` - * Automatic marshal and unmarshal for `JSON` and `XML` content type - * Default is `JSON`, if you supply `struct/map` without header `Content-Type` - * For auto-unmarshal, refer to - - - Success scenario [Request.SetResult()](https://pkg.go.dev/github.com/go-resty/resty/v2#Request.SetResult) and [Response.Result()](https://pkg.go.dev/github.com/go-resty/resty/v2#Response.Result). - - Error scenario [Request.SetError()](https://pkg.go.dev/github.com/go-resty/resty/v2#Request.SetError) and [Response.Error()](https://pkg.go.dev/github.com/go-resty/resty/v2#Response.Error). - - Supports [RFC7807](https://tools.ietf.org/html/rfc7807) - `application/problem+json` & `application/problem+xml` - * Resty provides an option to override [JSON Marshal/Unmarshal and XML Marshal/Unmarshal](#override-json--xml-marshalunmarshal) - * Easy to upload one or more file(s) via `multipart/form-data` - * Auto detects file content type - * Request URL [Path Params (aka URI Params)](https://pkg.go.dev/github.com/go-resty/resty/v2#Request.SetPathParams) - * Backoff Retry Mechanism with retry condition function [reference](retry_test.go) - * Resty client HTTP & REST [Request](https://pkg.go.dev/github.com/go-resty/resty/v2#Client.OnBeforeRequest) and [Response](https://pkg.go.dev/github.com/go-resty/resty/v2#Client.OnAfterResponse) middlewares - * `Request.SetContext` supported - * Authorization option of `BasicAuth` and `Bearer` token - * Set request `ContentLength` value for all request or particular request - * Custom [Root Certificates](https://pkg.go.dev/github.com/go-resty/resty/v2#Client.SetRootCertificate) and Client [Certificates](https://pkg.go.dev/github.com/go-resty/resty/v2#Client.SetCertificates) - * Download/Save HTTP response directly into File, like `curl -o` flag. See [SetOutputDirectory](https://pkg.go.dev/github.com/go-resty/resty/v2#Client.SetOutputDirectory) & [SetOutput](https://pkg.go.dev/github.com/go-resty/resty/v2#Request.SetOutput). - * Cookies for your request and CookieJar support - * SRV Record based request instead of Host URL - * Client settings like `Timeout`, `RedirectPolicy`, `Proxy`, `TLSClientConfig`, `Transport`, etc. - * Optionally allows GET request with payload, see [SetAllowGetMethodPayload](https://pkg.go.dev/github.com/go-resty/resty/v2#Client.SetAllowGetMethodPayload) - * Supports registering external JSON library into resty, see [how to use](https://github.com/go-resty/resty/issues/76#issuecomment-314015250) - * Exposes Response reader without reading response (no auto-unmarshaling) if need be, see [how to use](https://github.com/go-resty/resty/issues/87#issuecomment-322100604) - * Option to specify expected `Content-Type` when response `Content-Type` header missing. Refer to [#92](https://github.com/go-resty/resty/issues/92) - * Resty design - * Have client level settings & options and also override at Request level if you want to - * Request and Response middleware - * Create Multiple clients if you want to `resty.New()` - * Supports `http.RoundTripper` implementation, see [SetTransport](https://pkg.go.dev/github.com/go-resty/resty/v2#Client.SetTransport) - * goroutine concurrent safe - * Resty Client trace, see [Client.EnableTrace](https://pkg.go.dev/github.com/go-resty/resty/v2#Client.EnableTrace) and [Request.EnableTrace](https://pkg.go.dev/github.com/go-resty/resty/v2#Request.EnableTrace) - * Since v2.4.0, trace info contains a `RequestAttempt` value, and the `Request` object contains an `Attempt` attribute - * Debug mode - clean and informative logging presentation - * Gzip - Go does it automatically also resty has fallback handling too - * Works fine with `HTTP/2` and `HTTP/1.1` - * [Bazel support](#bazel-support) - * Easily mock Resty for testing, [for e.g.](#mocking-http-requests-using-httpmock-library) - * Well tested client library - -### Included Batteries - - * Redirect Policies - see [how to use](#redirect-policy) - * NoRedirectPolicy - * FlexibleRedirectPolicy - * DomainCheckRedirectPolicy - * etc. [more info](redirect.go) - * Retry Mechanism [how to use](#retries) - * Backoff Retry - * Conditional Retry - * Since v2.6.0, Retry Hooks - [Client](https://pkg.go.dev/github.com/go-resty/resty/v2#Client.AddRetryHook), [Request](https://pkg.go.dev/github.com/go-resty/resty/v2#Request.AddRetryHook) - * SRV Record based request instead of Host URL [how to use](resty_test.go#L1412) - * etc (upcoming - throw your idea's [here](https://github.com/go-resty/resty/issues)). - - -#### Supported Go Versions - -Initially Resty started supporting `go modules` since `v1.10.0` release. - -Starting Resty v2 and higher versions, it fully embraces [go modules](https://github.com/golang/go/wiki/Modules) package release. It requires a Go version capable of understanding `/vN` suffixed imports: - -- 1.9.7+ -- 1.10.3+ -- 1.11+ - - -## It might be beneficial for your project :smile: - -Resty author also published following projects for Go Community. - - * [aah framework](https://aahframework.org) - A secure, flexible, rapid Go web framework. - * [THUMBAI](https://thumbai.app) - Go Mod Repository, Go Vanity Service and Simple Proxy Server. - * [go-model](https://github.com/jeevatkm/go-model) - Robust & Easy to use model mapper and utility methods for Go `struct`. - - -## Installation - -```bash -# Go Modules -require github.com/go-resty/resty/v2 v2.7.0 -``` - -## Usage - -The following samples will assist you to become as comfortable as possible with resty library. - -```go -// Import resty into your code and refer it as `resty`. -import "github.com/go-resty/resty/v2" -``` - -#### Simple GET - -```go -// Create a Resty Client -client := resty.New() - -resp, err := client.R(). - EnableTrace(). - Get("https://httpbin.org/get") - -// Explore response object -fmt.Println("Response Info:") -fmt.Println(" Error :", err) -fmt.Println(" Status Code:", resp.StatusCode()) -fmt.Println(" Status :", resp.Status()) -fmt.Println(" Proto :", resp.Proto()) -fmt.Println(" Time :", resp.Time()) -fmt.Println(" Received At:", resp.ReceivedAt()) -fmt.Println(" Body :\n", resp) -fmt.Println() - -// Explore trace info -fmt.Println("Request Trace Info:") -ti := resp.Request.TraceInfo() -fmt.Println(" DNSLookup :", ti.DNSLookup) -fmt.Println(" ConnTime :", ti.ConnTime) -fmt.Println(" TCPConnTime :", ti.TCPConnTime) -fmt.Println(" TLSHandshake :", ti.TLSHandshake) -fmt.Println(" ServerTime :", ti.ServerTime) -fmt.Println(" ResponseTime :", ti.ResponseTime) -fmt.Println(" TotalTime :", ti.TotalTime) -fmt.Println(" IsConnReused :", ti.IsConnReused) -fmt.Println(" IsConnWasIdle :", ti.IsConnWasIdle) -fmt.Println(" ConnIdleTime :", ti.ConnIdleTime) -fmt.Println(" RequestAttempt:", ti.RequestAttempt) -fmt.Println(" RemoteAddr :", ti.RemoteAddr.String()) - -/* Output -Response Info: - Error : - Status Code: 200 - Status : 200 OK - Proto : HTTP/2.0 - Time : 457.034718ms - Received At: 2020-09-14 15:35:29.784681 -0700 PDT m=+0.458137045 - Body : - { - "args": {}, - "headers": { - "Accept-Encoding": "gzip", - "Host": "httpbin.org", - "User-Agent": "go-resty/2.4.0 (https://github.com/go-resty/resty)", - "X-Amzn-Trace-Id": "Root=1-5f5ff031-000ff6292204aa6898e4de49" - }, - "origin": "0.0.0.0", - "url": "https://httpbin.org/get" - } - -Request Trace Info: - DNSLookup : 4.074657ms - ConnTime : 381.709936ms - TCPConnTime : 77.428048ms - TLSHandshake : 299.623597ms - ServerTime : 75.414703ms - ResponseTime : 79.337µs - TotalTime : 457.034718ms - IsConnReused : false - IsConnWasIdle : false - ConnIdleTime : 0s - RequestAttempt: 1 - RemoteAddr : 3.221.81.55:443 -*/ -``` - -#### Enhanced GET - -```go -// Create a Resty Client -client := resty.New() - -resp, err := client.R(). - SetQueryParams(map[string]string{ - "page_no": "1", - "limit": "20", - "sort":"name", - "order": "asc", - "random":strconv.FormatInt(time.Now().Unix(), 10), - }). - SetHeader("Accept", "application/json"). - SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F"). - Get("/search_result") - - -// Sample of using Request.SetQueryString method -resp, err := client.R(). - SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more"). - SetHeader("Accept", "application/json"). - SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F"). - Get("/show_product") - - -// If necessary, you can force response content type to tell Resty to parse a JSON response into your struct -resp, err := client.R(). - SetResult(result). - ForceContentType("application/json"). - Get("v2/alpine/manifests/latest") -``` - -#### Various POST method combinations - -```go -// Create a Resty Client -client := resty.New() - -// POST JSON string -// No need to set content type, if you have client level setting -resp, err := client.R(). - SetHeader("Content-Type", "application/json"). - SetBody(`{"username":"testuser", "password":"testpass"}`). - SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}). - Post("https://myapp.com/login") - -// POST []byte array -// No need to set content type, if you have client level setting -resp, err := client.R(). - SetHeader("Content-Type", "application/json"). - SetBody([]byte(`{"username":"testuser", "password":"testpass"}`)). - SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}). - Post("https://myapp.com/login") - -// POST Struct, default is JSON content type. No need to set one -resp, err := client.R(). - SetBody(User{Username: "testuser", Password: "testpass"}). - SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}). - SetError(&AuthError{}). // or SetError(AuthError{}). - Post("https://myapp.com/login") - -// POST Map, default is JSON content type. No need to set one -resp, err := client.R(). - SetBody(map[string]interface{}{"username": "testuser", "password": "testpass"}). - SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}). - SetError(&AuthError{}). // or SetError(AuthError{}). - Post("https://myapp.com/login") - -// POST of raw bytes for file upload. For example: upload file to Dropbox -fileBytes, _ := ioutil.ReadFile("/Users/jeeva/mydocument.pdf") - -// See we are not setting content-type header, since go-resty automatically detects Content-Type for you -resp, err := client.R(). - SetBody(fileBytes). - SetContentLength(true). // Dropbox expects this value - SetAuthToken(""). - SetError(&DropboxError{}). // or SetError(DropboxError{}). - Post("https://content.dropboxapi.com/1/files_put/auto/resty/mydocument.pdf") // for upload Dropbox supports PUT too - -// Note: resty detects Content-Type for request body/payload if content type header is not set. -// * For struct and map data type defaults to 'application/json' -// * Fallback is plain text content type -``` - -#### Sample PUT - -You can use various combinations of `PUT` method call like demonstrated for `POST`. - -```go -// Note: This is one sample of PUT method usage, refer POST for more combination - -// Create a Resty Client -client := resty.New() - -// Request goes as JSON content type -// No need to set auth token, error, if you have client level settings -resp, err := client.R(). - SetBody(Article{ - Title: "go-resty", - Content: "This is my article content, oh ya!", - Author: "Jeevanandam M", - Tags: []string{"article", "sample", "resty"}, - }). - SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD"). - SetError(&Error{}). // or SetError(Error{}). - Put("https://myapp.com/article/1234") -``` - -#### Sample PATCH - -You can use various combinations of `PATCH` method call like demonstrated for `POST`. - -```go -// Note: This is one sample of PUT method usage, refer POST for more combination - -// Create a Resty Client -client := resty.New() - -// Request goes as JSON content type -// No need to set auth token, error, if you have client level settings -resp, err := client.R(). - SetBody(Article{ - Tags: []string{"new tag1", "new tag2"}, - }). - SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD"). - SetError(&Error{}). // or SetError(Error{}). - Patch("https://myapp.com/articles/1234") -``` - -#### Sample DELETE, HEAD, OPTIONS - -```go -// Create a Resty Client -client := resty.New() - -// DELETE a article -// No need to set auth token, error, if you have client level settings -resp, err := client.R(). - SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD"). - SetError(&Error{}). // or SetError(Error{}). - Delete("https://myapp.com/articles/1234") - -// DELETE a articles with payload/body as a JSON string -// No need to set auth token, error, if you have client level settings -resp, err := client.R(). - SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD"). - SetError(&Error{}). // or SetError(Error{}). - SetHeader("Content-Type", "application/json"). - SetBody(`{article_ids: [1002, 1006, 1007, 87683, 45432] }`). - Delete("https://myapp.com/articles") - -// HEAD of resource -// No need to set auth token, if you have client level settings -resp, err := client.R(). - SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD"). - Head("https://myapp.com/videos/hi-res-video") - -// OPTIONS of resource -// No need to set auth token, if you have client level settings -resp, err := client.R(). - SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD"). - Options("https://myapp.com/servers/nyc-dc-01") -``` - -#### Override JSON & XML Marshal/Unmarshal - -User could register choice of JSON/XML library into resty or write your own. By default resty registers standard `encoding/json` and `encoding/xml` respectively. -```go -// Example of registering json-iterator -import jsoniter "github.com/json-iterator/go" - -json := jsoniter.ConfigCompatibleWithStandardLibrary - -client := resty.New() -client.JSONMarshal = json.Marshal -client.JSONUnmarshal = json.Unmarshal - -// similarly user could do for XML too with - -client.XMLMarshal -client.XMLUnmarshal -``` - -### Multipart File(s) upload - -#### Using io.Reader - -```go -profileImgBytes, _ := ioutil.ReadFile("/Users/jeeva/test-img.png") -notesBytes, _ := ioutil.ReadFile("/Users/jeeva/text-file.txt") - -// Create a Resty Client -client := resty.New() - -resp, err := client.R(). - SetFileReader("profile_img", "test-img.png", bytes.NewReader(profileImgBytes)). - SetFileReader("notes", "text-file.txt", bytes.NewReader(notesBytes)). - SetFormData(map[string]string{ - "first_name": "Jeevanandam", - "last_name": "M", - }). - Post("http://myapp.com/upload") -``` - -#### Using File directly from Path - -```go -// Create a Resty Client -client := resty.New() - -// Single file scenario -resp, err := client.R(). - SetFile("profile_img", "/Users/jeeva/test-img.png"). - Post("http://myapp.com/upload") - -// Multiple files scenario -resp, err := client.R(). - SetFiles(map[string]string{ - "profile_img": "/Users/jeeva/test-img.png", - "notes": "/Users/jeeva/text-file.txt", - }). - Post("http://myapp.com/upload") - -// Multipart of form fields and files -resp, err := client.R(). - SetFiles(map[string]string{ - "profile_img": "/Users/jeeva/test-img.png", - "notes": "/Users/jeeva/text-file.txt", - }). - SetFormData(map[string]string{ - "first_name": "Jeevanandam", - "last_name": "M", - "zip_code": "00001", - "city": "my city", - "access_token": "C6A79608-782F-4ED0-A11D-BD82FAD829CD", - }). - Post("http://myapp.com/profile") -``` - -#### Sample Form submission - -```go -// Create a Resty Client -client := resty.New() - -// just mentioning about POST as an example with simple flow -// User Login -resp, err := client.R(). - SetFormData(map[string]string{ - "username": "jeeva", - "password": "mypass", - }). - Post("http://myapp.com/login") - -// Followed by profile update -resp, err := client.R(). - SetFormData(map[string]string{ - "first_name": "Jeevanandam", - "last_name": "M", - "zip_code": "00001", - "city": "new city update", - }). - Post("http://myapp.com/profile") - -// Multi value form data -criteria := url.Values{ - "search_criteria": []string{"book", "glass", "pencil"}, -} -resp, err := client.R(). - SetFormDataFromValues(criteria). - Post("http://myapp.com/search") -``` - -#### Save HTTP Response into File - -```go -// Create a Resty Client -client := resty.New() - -// Setting output directory path, If directory not exists then resty creates one! -// This is optional one, if you're planning using absoule path in -// `Request.SetOutput` and can used together. -client.SetOutputDirectory("/Users/jeeva/Downloads") - -// HTTP response gets saved into file, similar to curl -o flag -_, err := client.R(). - SetOutput("plugin/ReplyWithHeader-v5.1-beta.zip"). - Get("http://bit.ly/1LouEKr") - -// OR using absolute path -// Note: output directory path is not used for absolute path -_, err := client.R(). - SetOutput("/MyDownloads/plugin/ReplyWithHeader-v5.1-beta.zip"). - Get("http://bit.ly/1LouEKr") -``` - -#### Request URL Path Params - -Resty provides easy to use dynamic request URL path params. Params can be set at client and request level. Client level params value can be overridden at request level. - -```go -// Create a Resty Client -client := resty.New() - -client.R().SetPathParams(map[string]string{ - "userId": "sample@sample.com", - "subAccountId": "100002", -}). -Get("/v1/users/{userId}/{subAccountId}/details") - -// Result: -// Composed URL - /v1/users/sample@sample.com/100002/details -``` - -#### Request and Response Middleware - -Resty provides middleware ability to manipulate for Request and Response. It is more flexible than callback approach. - -```go -// Create a Resty Client -client := resty.New() - -// Registering Request Middleware -client.OnBeforeRequest(func(c *resty.Client, req *resty.Request) error { - // Now you have access to Client and current Request object - // manipulate it as per your need - - return nil // if its success otherwise return error - }) - -// Registering Response Middleware -client.OnAfterResponse(func(c *resty.Client, resp *resty.Response) error { - // Now you have access to Client and current Response object - // manipulate it as per your need - - return nil // if its success otherwise return error - }) -``` - -#### OnError Hooks - -Resty provides OnError hooks that may be called because: - -- The client failed to send the request due to connection timeout, TLS handshake failure, etc... -- The request was retried the maximum amount of times, and still failed. - -If there was a response from the server, the original error will be wrapped in `*resty.ResponseError` which contains the last response received. - -```go -// Create a Resty Client -client := resty.New() - -client.OnError(func(req *resty.Request, err error) { - if v, ok := err.(*resty.ResponseError); ok { - // v.Response contains the last response from the server - // v.Err contains the original error - } - // Log the error, increment a metric, etc... -}) -``` - -#### Redirect Policy - -Resty provides few ready to use redirect policy(s) also it supports multiple policies together. - -```go -// Create a Resty Client -client := resty.New() - -// Assign Client Redirect Policy. Create one as per you need -client.SetRedirectPolicy(resty.FlexibleRedirectPolicy(15)) - -// Wanna multiple policies such as redirect count, domain name check, etc -client.SetRedirectPolicy(resty.FlexibleRedirectPolicy(20), - resty.DomainCheckRedirectPolicy("host1.com", "host2.org", "host3.net")) -``` - -##### Custom Redirect Policy - -Implement [RedirectPolicy](redirect.go#L20) interface and register it with resty client. Have a look [redirect.go](redirect.go) for more information. - -```go -// Create a Resty Client -client := resty.New() - -// Using raw func into resty.SetRedirectPolicy -client.SetRedirectPolicy(resty.RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error { - // Implement your logic here - - // return nil for continue redirect otherwise return error to stop/prevent redirect - return nil -})) - -//--------------------------------------------------- - -// Using struct create more flexible redirect policy -type CustomRedirectPolicy struct { - // variables goes here -} - -func (c *CustomRedirectPolicy) Apply(req *http.Request, via []*http.Request) error { - // Implement your logic here - - // return nil for continue redirect otherwise return error to stop/prevent redirect - return nil -} - -// Registering in resty -client.SetRedirectPolicy(CustomRedirectPolicy{/* initialize variables */}) -``` - -#### Custom Root Certificates and Client Certificates - -```go -// Create a Resty Client -client := resty.New() - -// Custom Root certificates, just supply .pem file. -// you can add one or more root certificates, its get appended -client.SetRootCertificate("/path/to/root/pemFile1.pem") -client.SetRootCertificate("/path/to/root/pemFile2.pem") -// ... and so on! - -// Adding Client Certificates, you add one or more certificates -// Sample for creating certificate object -// Parsing public/private key pair from a pair of files. The files must contain PEM encoded data. -cert1, err := tls.LoadX509KeyPair("certs/client.pem", "certs/client.key") -if err != nil { - log.Fatalf("ERROR client certificate: %s", err) -} -// ... - -// You add one or more certificates -client.SetCertificates(cert1, cert2, cert3) -``` - -#### Custom Root Certificates and Client Certificates from string - -```go -// Custom Root certificates from string -// You can pass you certificates throught env variables as strings -// you can add one or more root certificates, its get appended -client.SetRootCertificateFromString("-----BEGIN CERTIFICATE-----content-----END CERTIFICATE-----") -client.SetRootCertificateFromString("-----BEGIN CERTIFICATE-----content-----END CERTIFICATE-----") -// ... and so on! - -// Adding Client Certificates, you add one or more certificates -// Sample for creating certificate object -// Parsing public/private key pair from a pair of files. The files must contain PEM encoded data. -cert1, err := tls.X509KeyPair([]byte("-----BEGIN CERTIFICATE-----content-----END CERTIFICATE-----"), []byte("-----BEGIN CERTIFICATE-----content-----END CERTIFICATE-----")) -if err != nil { - log.Fatalf("ERROR client certificate: %s", err) -} -// ... - -// You add one or more certificates -client.SetCertificates(cert1, cert2, cert3) -``` - -#### Proxy Settings - Client as well as at Request Level - -Default `Go` supports Proxy via environment variable `HTTP_PROXY`. Resty provides support via `SetProxy` & `RemoveProxy`. -Choose as per your need. - -**Client Level Proxy** settings applied to all the request - -```go -// Create a Resty Client -client := resty.New() - -// Setting a Proxy URL and Port -client.SetProxy("http://proxyserver:8888") - -// Want to remove proxy setting -client.RemoveProxy() -``` - -#### Retries - -Resty uses [backoff](http://www.awsarchitectureblog.com/2015/03/backoff.html) -to increase retry intervals after each attempt. - -Usage example: - -```go -// Create a Resty Client -client := resty.New() - -// Retries are configured per client -client. - // Set retry count to non zero to enable retries - SetRetryCount(3). - // You can override initial retry wait time. - // Default is 100 milliseconds. - SetRetryWaitTime(5 * time.Second). - // MaxWaitTime can be overridden as well. - // Default is 2 seconds. - SetRetryMaxWaitTime(20 * time.Second). - // SetRetryAfter sets callback to calculate wait time between retries. - // Default (nil) implies exponential backoff with jitter - SetRetryAfter(func(client *resty.Client, resp *resty.Response) (time.Duration, error) { - return 0, errors.New("quota exceeded") - }) -``` - -Above setup will result in resty retrying requests returned non nil error up to -3 times with delay increased after each attempt. - -You can optionally provide client with [custom retry conditions](https://pkg.go.dev/github.com/go-resty/resty/v2#RetryConditionFunc): - -```go -// Create a Resty Client -client := resty.New() - -client.AddRetryCondition( - // RetryConditionFunc type is for retry condition function - // input: non-nil Response OR request execution error - func(r *resty.Response, err error) bool { - return r.StatusCode() == http.StatusTooManyRequests - }, -) -``` - -Above example will make resty retry requests ended with `429 Too Many Requests` -status code. - -Multiple retry conditions can be added. - -It is also possible to use `resty.Backoff(...)` to get arbitrary retry scenarios -implemented. [Reference](retry_test.go). - -#### Allow GET request with Payload - -```go -// Create a Resty Client -client := resty.New() - -// Allow GET request with Payload. This is disabled by default. -client.SetAllowGetMethodPayload(true) -``` - -#### Wanna Multiple Clients - -```go -// Here you go! -// Client 1 -client1 := resty.New() -client1.R().Get("http://httpbin.org") -// ... - -// Client 2 -client2 := resty.New() -client2.R().Head("http://httpbin.org") -// ... - -// Bend it as per your need!!! -``` - -#### Remaining Client Settings & its Options - -```go -// Create a Resty Client -client := resty.New() - -// Unique settings at Client level -//-------------------------------- -// Enable debug mode -client.SetDebug(true) - -// Assign Client TLSClientConfig -// One can set custom root-certificate. Refer: http://golang.org/pkg/crypto/tls/#example_Dial -client.SetTLSClientConfig(&tls.Config{ RootCAs: roots }) - -// or One can disable security check (https) -client.SetTLSClientConfig(&tls.Config{ InsecureSkipVerify: true }) - -// Set client timeout as per your need -client.SetTimeout(1 * time.Minute) - - -// You can override all below settings and options at request level if you want to -//-------------------------------------------------------------------------------- -// Host URL for all request. So you can use relative URL in the request -client.SetHostURL("http://httpbin.org") - -// Headers for all request -client.SetHeader("Accept", "application/json") -client.SetHeaders(map[string]string{ - "Content-Type": "application/json", - "User-Agent": "My custom User Agent String", - }) - -// Cookies for all request -client.SetCookie(&http.Cookie{ - Name:"go-resty", - Value:"This is cookie value", - Path: "/", - Domain: "sample.com", - MaxAge: 36000, - HttpOnly: true, - Secure: false, - }) -client.SetCookies(cookies) - -// URL query parameters for all request -client.SetQueryParam("user_id", "00001") -client.SetQueryParams(map[string]string{ // sample of those who use this manner - "api_key": "api-key-here", - "api_secert": "api-secert", - }) -client.R().SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more") - -// Form data for all request. Typically used with POST and PUT -client.SetFormData(map[string]string{ - "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F", - }) - -// Basic Auth for all request -client.SetBasicAuth("myuser", "mypass") - -// Bearer Auth Token for all request -client.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F") - -// Enabling Content length value for all request -client.SetContentLength(true) - -// Registering global Error object structure for JSON/XML request -client.SetError(&Error{}) // or resty.SetError(Error{}) -``` - -#### Unix Socket - -```go -unixSocket := "/var/run/my_socket.sock" - -// Create a Go's http.Transport so we can set it in resty. -transport := http.Transport{ - Dial: func(_, _ string) (net.Conn, error) { - return net.Dial("unix", unixSocket) - }, -} - -// Create a Resty Client -client := resty.New() - -// Set the previous transport that we created, set the scheme of the communication to the -// socket and set the unixSocket as the HostURL. -client.SetTransport(&transport).SetScheme("http").SetHostURL(unixSocket) - -// No need to write the host's URL on the request, just the path. -client.R().Get("/index.html") -``` - -#### Bazel Support - -Resty can be built, tested and depended upon via [Bazel](https://bazel.build). -For example, to run all tests: - -```shell -bazel test :resty_test -``` - -#### Mocking http requests using [httpmock](https://github.com/jarcoal/httpmock) library - -In order to mock the http requests when testing your application you -could use the `httpmock` library. - -When using the default resty client, you should pass the client to the library as follow: - -```go -// Create a Resty Client -client := resty.New() - -// Get the underlying HTTP Client and set it to Mock -httpmock.ActivateNonDefault(client.GetClient()) -``` - -More detailed example of mocking resty http requests using ginko could be found [here](https://github.com/jarcoal/httpmock#ginkgo--resty-example). - -## Versioning - -Resty releases versions according to [Semantic Versioning](http://semver.org) - - * Resty v2 does not use `gopkg.in` service for library versioning. - * Resty fully adapted to `go mod` capabilities since `v1.10.0` release. - * Resty v1 series was using `gopkg.in` to provide versioning. `gopkg.in/resty.vX` points to appropriate tagged versions; `X` denotes version series number and it's a stable release for production use. For e.g. `gopkg.in/resty.v0`. - * Development takes place at the master branch. Although the code in master should always compile and test successfully, it might break API's. I aim to maintain backwards compatibility, but sometimes API's and behavior might be changed to fix a bug. - -## Contribution - -I would welcome your contribution! If you find any improvement or issue you want to fix, feel free to send a pull request, I like pull requests that include test cases for fix/enhancement. I have done my best to bring pretty good code coverage. Feel free to write tests. - -BTW, I'd like to know what you think about `Resty`. Kindly open an issue or send me an email; it'd mean a lot to me. - -## Creator - -[Jeevanandam M.](https://github.com/jeevatkm) (jeeva@myjeeva.com) - -## Core Team - -Have a look on [Members](https://github.com/orgs/go-resty/people) page. - -## Contributors - -Have a look on [Contributors](https://github.com/go-resty/resty/graphs/contributors) page. - -## License - -Resty released under MIT license, refer [LICENSE](LICENSE) file. diff --git a/vendor/github.com/go-resty/resty/v2/WORKSPACE b/vendor/github.com/go-resty/resty/v2/WORKSPACE deleted file mode 100644 index 9ef03e95..00000000 --- a/vendor/github.com/go-resty/resty/v2/WORKSPACE +++ /dev/null @@ -1,31 +0,0 @@ -workspace(name = "resty") - -load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") - -http_archive( - name = "io_bazel_rules_go", - sha256 = "69de5c704a05ff37862f7e0f5534d4f479418afc21806c887db544a316f3cb6b", - urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.27.0/rules_go-v0.27.0.tar.gz", - "https://github.com/bazelbuild/rules_go/releases/download/v0.27.0/rules_go-v0.27.0.tar.gz", - ], -) - -http_archive( - name = "bazel_gazelle", - sha256 = "62ca106be173579c0a167deb23358fdfe71ffa1e4cfdddf5582af26520f1c66f", - urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.23.0/bazel-gazelle-v0.23.0.tar.gz", - "https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.23.0/bazel-gazelle-v0.23.0.tar.gz", - ], -) - -load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies") - -go_rules_dependencies() - -go_register_toolchains(version = "1.16") - -load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies") - -gazelle_dependencies() diff --git a/vendor/github.com/go-resty/resty/v2/client.go b/vendor/github.com/go-resty/resty/v2/client.go deleted file mode 100644 index 1a03efa3..00000000 --- a/vendor/github.com/go-resty/resty/v2/client.go +++ /dev/null @@ -1,1115 +0,0 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "bytes" - "compress/gzip" - "crypto/tls" - "crypto/x509" - "encoding/json" - "encoding/xml" - "errors" - "fmt" - "io" - "io/ioutil" - "math" - "net/http" - "net/url" - "reflect" - "regexp" - "strings" - "sync" - "time" -) - -const ( - // MethodGet HTTP method - MethodGet = "GET" - - // MethodPost HTTP method - MethodPost = "POST" - - // MethodPut HTTP method - MethodPut = "PUT" - - // MethodDelete HTTP method - MethodDelete = "DELETE" - - // MethodPatch HTTP method - MethodPatch = "PATCH" - - // MethodHead HTTP method - MethodHead = "HEAD" - - // MethodOptions HTTP method - MethodOptions = "OPTIONS" -) - -var ( - hdrUserAgentKey = http.CanonicalHeaderKey("User-Agent") - hdrAcceptKey = http.CanonicalHeaderKey("Accept") - hdrContentTypeKey = http.CanonicalHeaderKey("Content-Type") - hdrContentLengthKey = http.CanonicalHeaderKey("Content-Length") - hdrContentEncodingKey = http.CanonicalHeaderKey("Content-Encoding") - hdrLocationKey = http.CanonicalHeaderKey("Location") - - plainTextType = "text/plain; charset=utf-8" - jsonContentType = "application/json" - formContentType = "application/x-www-form-urlencoded" - - jsonCheck = regexp.MustCompile(`(?i:(application|text)/(json|.*\+json|json\-.*)(;|$))`) - xmlCheck = regexp.MustCompile(`(?i:(application|text)/(xml|.*\+xml)(;|$))`) - - hdrUserAgentValue = "go-resty/" + Version + " (https://github.com/go-resty/resty)" - bufPool = &sync.Pool{New: func() interface{} { return &bytes.Buffer{} }} -) - -type ( - // RequestMiddleware type is for request middleware, called before a request is sent - RequestMiddleware func(*Client, *Request) error - - // ResponseMiddleware type is for response middleware, called after a response has been received - ResponseMiddleware func(*Client, *Response) error - - // PreRequestHook type is for the request hook, called right before the request is sent - PreRequestHook func(*Client, *http.Request) error - - // RequestLogCallback type is for request logs, called before the request is logged - RequestLogCallback func(*RequestLog) error - - // ResponseLogCallback type is for response logs, called before the response is logged - ResponseLogCallback func(*ResponseLog) error - - // ErrorHook type is for reacting to request errors, called after all retries were attempted - ErrorHook func(*Request, error) -) - -// Client struct is used to create Resty client with client level settings, -// these settings are applicable to all the request raised from the client. -// -// Resty also provides an options to override most of the client settings -// at request level. -type Client struct { - BaseURL string - HostURL string // Deprecated: use BaseURL instead. To be removed in v3.0.0 release. - QueryParam url.Values - FormData url.Values - PathParams map[string]string - Header http.Header - UserInfo *User - Token string - AuthScheme string - Cookies []*http.Cookie - Error reflect.Type - Debug bool - DisableWarn bool - AllowGetMethodPayload bool - RetryCount int - RetryWaitTime time.Duration - RetryMaxWaitTime time.Duration - RetryConditions []RetryConditionFunc - RetryHooks []OnRetryFunc - RetryAfter RetryAfterFunc - JSONMarshal func(v interface{}) ([]byte, error) - JSONUnmarshal func(data []byte, v interface{}) error - XMLMarshal func(v interface{}) ([]byte, error) - XMLUnmarshal func(data []byte, v interface{}) error - - // HeaderAuthorizationKey is used to set/access Request Authorization header - // value when `SetAuthToken` option is used. - HeaderAuthorizationKey string - - jsonEscapeHTML bool - setContentLength bool - closeConnection bool - notParseResponse bool - trace bool - debugBodySizeLimit int64 - outputDirectory string - scheme string - log Logger - httpClient *http.Client - proxyURL *url.URL - beforeRequest []RequestMiddleware - udBeforeRequest []RequestMiddleware - preReqHook PreRequestHook - afterResponse []ResponseMiddleware - requestLog RequestLogCallback - responseLog ResponseLogCallback - errorHooks []ErrorHook -} - -// User type is to hold an username and password information -type User struct { - Username, Password string -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Client methods -//___________________________________ - -// SetHostURL method is to set Host URL in the client instance. It will be used with request -// raised from this client with relative URL -// // Setting HTTP address -// client.SetHostURL("http://myjeeva.com") -// -// // Setting HTTPS address -// client.SetHostURL("https://myjeeva.com") -// -// Deprecated: use SetBaseURL instead. To be removed in v3.0.0 release. -func (c *Client) SetHostURL(url string) *Client { - c.SetBaseURL(url) - return c -} - -// SetBaseURL method is to set Base URL in the client instance. It will be used with request -// raised from this client with relative URL -// // Setting HTTP address -// client.SetBaseURL("http://myjeeva.com") -// -// // Setting HTTPS address -// client.SetBaseURL("https://myjeeva.com") -// -// Since v2.7.0 -func (c *Client) SetBaseURL(url string) *Client { - c.BaseURL = strings.TrimRight(url, "/") - c.HostURL = c.BaseURL - return c -} - -// SetHeader method sets a single header field and its value in the client instance. -// These headers will be applied to all requests raised from this client instance. -// Also it can be overridden at request level header options. -// -// See `Request.SetHeader` or `Request.SetHeaders`. -// -// For Example: To set `Content-Type` and `Accept` as `application/json` -// -// client. -// SetHeader("Content-Type", "application/json"). -// SetHeader("Accept", "application/json") -func (c *Client) SetHeader(header, value string) *Client { - c.Header.Set(header, value) - return c -} - -// SetHeaders method sets multiple headers field and its values at one go in the client instance. -// These headers will be applied to all requests raised from this client instance. Also it can be -// overridden at request level headers options. -// -// See `Request.SetHeaders` or `Request.SetHeader`. -// -// For Example: To set `Content-Type` and `Accept` as `application/json` -// -// client.SetHeaders(map[string]string{ -// "Content-Type": "application/json", -// "Accept": "application/json", -// }) -func (c *Client) SetHeaders(headers map[string]string) *Client { - for h, v := range headers { - c.Header.Set(h, v) - } - return c -} - -// SetHeaderVerbatim method is to set a single header field and its value verbatim in the current request. -// -// For Example: To set `all_lowercase` and `UPPERCASE` as `available`. -// client.R(). -// SetHeaderVerbatim("all_lowercase", "available"). -// SetHeaderVerbatim("UPPERCASE", "available") -// -// Also you can override header value, which was set at client instance level. -// -// Since v2.6.0 -func (c *Client) SetHeaderVerbatim(header, value string) *Client { - c.Header[header] = []string{value} - return c -} - -// SetCookieJar method sets custom http.CookieJar in the resty client. Its way to override default. -// -// For Example: sometimes we don't want to save cookies in api contacting, we can remove the default -// CookieJar in resty client. -// -// client.SetCookieJar(nil) -func (c *Client) SetCookieJar(jar http.CookieJar) *Client { - c.httpClient.Jar = jar - return c -} - -// SetCookie method appends a single cookie in the client instance. -// These cookies will be added to all the request raised from this client instance. -// client.SetCookie(&http.Cookie{ -// Name:"go-resty", -// Value:"This is cookie value", -// }) -func (c *Client) SetCookie(hc *http.Cookie) *Client { - c.Cookies = append(c.Cookies, hc) - return c -} - -// SetCookies method sets an array of cookies in the client instance. -// These cookies will be added to all the request raised from this client instance. -// cookies := []*http.Cookie{ -// &http.Cookie{ -// Name:"go-resty-1", -// Value:"This is cookie 1 value", -// }, -// &http.Cookie{ -// Name:"go-resty-2", -// Value:"This is cookie 2 value", -// }, -// } -// -// // Setting a cookies into resty -// client.SetCookies(cookies) -func (c *Client) SetCookies(cs []*http.Cookie) *Client { - c.Cookies = append(c.Cookies, cs...) - return c -} - -// SetQueryParam method sets single parameter and its value in the client instance. -// It will be formed as query string for the request. -// -// For Example: `search=kitchen%20papers&size=large` -// in the URL after `?` mark. These query params will be added to all the request raised from -// this client instance. Also it can be overridden at request level Query Param options. -// -// See `Request.SetQueryParam` or `Request.SetQueryParams`. -// client. -// SetQueryParam("search", "kitchen papers"). -// SetQueryParam("size", "large") -func (c *Client) SetQueryParam(param, value string) *Client { - c.QueryParam.Set(param, value) - return c -} - -// SetQueryParams method sets multiple parameters and their values at one go in the client instance. -// It will be formed as query string for the request. -// -// For Example: `search=kitchen%20papers&size=large` -// in the URL after `?` mark. These query params will be added to all the request raised from this -// client instance. Also it can be overridden at request level Query Param options. -// -// See `Request.SetQueryParams` or `Request.SetQueryParam`. -// client.SetQueryParams(map[string]string{ -// "search": "kitchen papers", -// "size": "large", -// }) -func (c *Client) SetQueryParams(params map[string]string) *Client { - for p, v := range params { - c.SetQueryParam(p, v) - } - return c -} - -// SetFormData method sets Form parameters and their values in the client instance. -// It's applicable only HTTP method `POST` and `PUT` and requets content type would be set as -// `application/x-www-form-urlencoded`. These form data will be added to all the request raised from -// this client instance. Also it can be overridden at request level form data. -// -// See `Request.SetFormData`. -// client.SetFormData(map[string]string{ -// "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F", -// "user_id": "3455454545", -// }) -func (c *Client) SetFormData(data map[string]string) *Client { - for k, v := range data { - c.FormData.Set(k, v) - } - return c -} - -// SetBasicAuth method sets the basic authentication header in the HTTP request. For Example: -// Authorization: Basic -// -// For Example: To set the header for username "go-resty" and password "welcome" -// client.SetBasicAuth("go-resty", "welcome") -// -// This basic auth information gets added to all the request rasied from this client instance. -// Also it can be overridden or set one at the request level is supported. -// -// See `Request.SetBasicAuth`. -func (c *Client) SetBasicAuth(username, password string) *Client { - c.UserInfo = &User{Username: username, Password: password} - return c -} - -// SetAuthToken method sets the auth token of the `Authorization` header for all HTTP requests. -// The default auth scheme is `Bearer`, it can be customized with the method `SetAuthScheme`. For Example: -// Authorization: -// -// For Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F -// -// client.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F") -// -// This auth token gets added to all the requests rasied from this client instance. -// Also it can be overridden or set one at the request level is supported. -// -// See `Request.SetAuthToken`. -func (c *Client) SetAuthToken(token string) *Client { - c.Token = token - return c -} - -// SetAuthScheme method sets the auth scheme type in the HTTP request. For Example: -// Authorization: -// -// For Example: To set the scheme to use OAuth -// -// client.SetAuthScheme("OAuth") -// -// This auth scheme gets added to all the requests rasied from this client instance. -// Also it can be overridden or set one at the request level is supported. -// -// Information about auth schemes can be found in RFC7235 which is linked to below -// along with the page containing the currently defined official authentication schemes: -// https://tools.ietf.org/html/rfc7235 -// https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes -// -// See `Request.SetAuthToken`. -func (c *Client) SetAuthScheme(scheme string) *Client { - c.AuthScheme = scheme - return c -} - -// R method creates a new request instance, its used for Get, Post, Put, Delete, Patch, Head, Options, etc. -func (c *Client) R() *Request { - r := &Request{ - QueryParam: url.Values{}, - FormData: url.Values{}, - Header: http.Header{}, - Cookies: make([]*http.Cookie, 0), - - client: c, - multipartFiles: []*File{}, - multipartFields: []*MultipartField{}, - PathParams: map[string]string{}, - jsonEscapeHTML: true, - } - return r -} - -// NewRequest is an alias for method `R()`. Creates a new request instance, its used for -// Get, Post, Put, Delete, Patch, Head, Options, etc. -func (c *Client) NewRequest() *Request { - return c.R() -} - -// OnBeforeRequest method appends request middleware into the before request chain. -// Its gets applied after default Resty request middlewares and before request -// been sent from Resty to host server. -// client.OnBeforeRequest(func(c *resty.Client, r *resty.Request) error { -// // Now you have access to Client and Request instance -// // manipulate it as per your need -// -// return nil // if its success otherwise return error -// }) -func (c *Client) OnBeforeRequest(m RequestMiddleware) *Client { - c.udBeforeRequest = append(c.udBeforeRequest, m) - return c -} - -// OnAfterResponse method appends response middleware into the after response chain. -// Once we receive response from host server, default Resty response middleware -// gets applied and then user assigened response middlewares applied. -// client.OnAfterResponse(func(c *resty.Client, r *resty.Response) error { -// // Now you have access to Client and Response instance -// // manipulate it as per your need -// -// return nil // if its success otherwise return error -// }) -func (c *Client) OnAfterResponse(m ResponseMiddleware) *Client { - c.afterResponse = append(c.afterResponse, m) - return c -} - -// OnError method adds a callback that will be run whenever a request execution fails. -// This is called after all retries have been attempted (if any). -// If there was a response from the server, the error will be wrapped in *ResponseError -// which has the last response received from the server. -// -// client.OnError(func(req *resty.Request, err error) { -// if v, ok := err.(*resty.ResponseError); ok { -// // Do something with v.Response -// } -// // Log the error, increment a metric, etc... -// }) -func (c *Client) OnError(h ErrorHook) *Client { - c.errorHooks = append(c.errorHooks, h) - return c -} - -// SetPreRequestHook method sets the given pre-request function into resty client. -// It is called right before the request is fired. -// -// Note: Only one pre-request hook can be registered. Use `client.OnBeforeRequest` for mutilple. -func (c *Client) SetPreRequestHook(h PreRequestHook) *Client { - if c.preReqHook != nil { - c.log.Warnf("Overwriting an existing pre-request hook: %s", functionName(h)) - } - c.preReqHook = h - return c -} - -// SetDebug method enables the debug mode on Resty client. Client logs details of every request and response. -// For `Request` it logs information such as HTTP verb, Relative URL path, Host, Headers, Body if it has one. -// For `Response` it logs information such as Status, Response Time, Headers, Body if it has one. -// client.SetDebug(true) -func (c *Client) SetDebug(d bool) *Client { - c.Debug = d - return c -} - -// SetDebugBodyLimit sets the maximum size for which the response and request body will be logged in debug mode. -// client.SetDebugBodyLimit(1000000) -func (c *Client) SetDebugBodyLimit(sl int64) *Client { - c.debugBodySizeLimit = sl - return c -} - -// OnRequestLog method used to set request log callback into Resty. Registered callback gets -// called before the resty actually logs the information. -func (c *Client) OnRequestLog(rl RequestLogCallback) *Client { - if c.requestLog != nil { - c.log.Warnf("Overwriting an existing on-request-log callback from=%s to=%s", - functionName(c.requestLog), functionName(rl)) - } - c.requestLog = rl - return c -} - -// OnResponseLog method used to set response log callback into Resty. Registered callback gets -// called before the resty actually logs the information. -func (c *Client) OnResponseLog(rl ResponseLogCallback) *Client { - if c.responseLog != nil { - c.log.Warnf("Overwriting an existing on-response-log callback from=%s to=%s", - functionName(c.responseLog), functionName(rl)) - } - c.responseLog = rl - return c -} - -// SetDisableWarn method disables the warning message on Resty client. -// -// For Example: Resty warns the user when BasicAuth used on non-TLS mode. -// client.SetDisableWarn(true) -func (c *Client) SetDisableWarn(d bool) *Client { - c.DisableWarn = d - return c -} - -// SetAllowGetMethodPayload method allows the GET method with payload on Resty client. -// -// For Example: Resty allows the user sends request with a payload on HTTP GET method. -// client.SetAllowGetMethodPayload(true) -func (c *Client) SetAllowGetMethodPayload(a bool) *Client { - c.AllowGetMethodPayload = a - return c -} - -// SetLogger method sets given writer for logging Resty request and response details. -// -// Compliant to interface `resty.Logger`. -func (c *Client) SetLogger(l Logger) *Client { - c.log = l - return c -} - -// SetContentLength method enables the HTTP header `Content-Length` value for every request. -// By default Resty won't set `Content-Length`. -// client.SetContentLength(true) -// -// Also you have an option to enable for particular request. See `Request.SetContentLength` -func (c *Client) SetContentLength(l bool) *Client { - c.setContentLength = l - return c -} - -// SetTimeout method sets timeout for request raised from client. -// client.SetTimeout(time.Duration(1 * time.Minute)) -func (c *Client) SetTimeout(timeout time.Duration) *Client { - c.httpClient.Timeout = timeout - return c -} - -// SetError method is to register the global or client common `Error` object into Resty. -// It is used for automatic unmarshalling if response status code is greater than 399 and -// content type either JSON or XML. Can be pointer or non-pointer. -// client.SetError(&Error{}) -// // OR -// client.SetError(Error{}) -func (c *Client) SetError(err interface{}) *Client { - c.Error = typeOf(err) - return c -} - -// SetRedirectPolicy method sets the client redirect poilicy. Resty provides ready to use -// redirect policies. Wanna create one for yourself refer to `redirect.go`. -// -// client.SetRedirectPolicy(FlexibleRedirectPolicy(20)) -// -// // Need multiple redirect policies together -// client.SetRedirectPolicy(FlexibleRedirectPolicy(20), DomainCheckRedirectPolicy("host1.com", "host2.net")) -func (c *Client) SetRedirectPolicy(policies ...interface{}) *Client { - for _, p := range policies { - if _, ok := p.(RedirectPolicy); !ok { - c.log.Errorf("%v does not implement resty.RedirectPolicy (missing Apply method)", - functionName(p)) - } - } - - c.httpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error { - for _, p := range policies { - if err := p.(RedirectPolicy).Apply(req, via); err != nil { - return err - } - } - return nil // looks good, go ahead - } - - return c -} - -// SetRetryCount method enables retry on Resty client and allows you -// to set no. of retry count. Resty uses a Backoff mechanism. -func (c *Client) SetRetryCount(count int) *Client { - c.RetryCount = count - return c -} - -// SetRetryWaitTime method sets default wait time to sleep before retrying -// request. -// -// Default is 100 milliseconds. -func (c *Client) SetRetryWaitTime(waitTime time.Duration) *Client { - c.RetryWaitTime = waitTime - return c -} - -// SetRetryMaxWaitTime method sets max wait time to sleep before retrying -// request. -// -// Default is 2 seconds. -func (c *Client) SetRetryMaxWaitTime(maxWaitTime time.Duration) *Client { - c.RetryMaxWaitTime = maxWaitTime - return c -} - -// SetRetryAfter sets callback to calculate wait time between retries. -// Default (nil) implies exponential backoff with jitter -func (c *Client) SetRetryAfter(callback RetryAfterFunc) *Client { - c.RetryAfter = callback - return c -} - -// AddRetryCondition method adds a retry condition function to array of functions -// that are checked to determine if the request is retried. The request will -// retry if any of the functions return true and error is nil. -// -// Note: These retry conditions are applied on all Request made using this Client. -// For Request specific retry conditions check *Request.AddRetryCondition -func (c *Client) AddRetryCondition(condition RetryConditionFunc) *Client { - c.RetryConditions = append(c.RetryConditions, condition) - return c -} - -// AddRetryAfterErrorCondition adds the basic condition of retrying after encountering -// an error from the http response -// -// Since v2.6.0 -func (c *Client) AddRetryAfterErrorCondition() *Client { - c.AddRetryCondition(func(response *Response, err error) bool { - return response.IsError() - }) - return c -} - -// AddRetryHook adds a side-effecting retry hook to an array of hooks -// that will be executed on each retry. -// -// Since v2.6.0 -func (c *Client) AddRetryHook(hook OnRetryFunc) *Client { - c.RetryHooks = append(c.RetryHooks, hook) - return c -} - -// SetTLSClientConfig method sets TLSClientConfig for underling client Transport. -// -// For Example: -// // One can set custom root-certificate. Refer: http://golang.org/pkg/crypto/tls/#example_Dial -// client.SetTLSClientConfig(&tls.Config{ RootCAs: roots }) -// -// // or One can disable security check (https) -// client.SetTLSClientConfig(&tls.Config{ InsecureSkipVerify: true }) -// -// Note: This method overwrites existing `TLSClientConfig`. -func (c *Client) SetTLSClientConfig(config *tls.Config) *Client { - transport, err := c.transport() - if err != nil { - c.log.Errorf("%v", err) - return c - } - transport.TLSClientConfig = config - return c -} - -// SetProxy method sets the Proxy URL and Port for Resty client. -// client.SetProxy("http://proxyserver:8888") -// -// OR Without this `SetProxy` method, you could also set Proxy via environment variable. -// -// Refer to godoc `http.ProxyFromEnvironment`. -func (c *Client) SetProxy(proxyURL string) *Client { - transport, err := c.transport() - if err != nil { - c.log.Errorf("%v", err) - return c - } - - pURL, err := url.Parse(proxyURL) - if err != nil { - c.log.Errorf("%v", err) - return c - } - - c.proxyURL = pURL - transport.Proxy = http.ProxyURL(c.proxyURL) - return c -} - -// RemoveProxy method removes the proxy configuration from Resty client -// client.RemoveProxy() -func (c *Client) RemoveProxy() *Client { - transport, err := c.transport() - if err != nil { - c.log.Errorf("%v", err) - return c - } - c.proxyURL = nil - transport.Proxy = nil - return c -} - -// SetCertificates method helps to set client certificates into Resty conveniently. -func (c *Client) SetCertificates(certs ...tls.Certificate) *Client { - config, err := c.tlsConfig() - if err != nil { - c.log.Errorf("%v", err) - return c - } - config.Certificates = append(config.Certificates, certs...) - return c -} - -// SetRootCertificate method helps to add one or more root certificates into Resty client -// client.SetRootCertificate("/path/to/root/pemFile.pem") -func (c *Client) SetRootCertificate(pemFilePath string) *Client { - rootPemData, err := ioutil.ReadFile(pemFilePath) - if err != nil { - c.log.Errorf("%v", err) - return c - } - - config, err := c.tlsConfig() - if err != nil { - c.log.Errorf("%v", err) - return c - } - if config.RootCAs == nil { - config.RootCAs = x509.NewCertPool() - } - - config.RootCAs.AppendCertsFromPEM(rootPemData) - return c -} - -// SetRootCertificateFromString method helps to add one or more root certificates into Resty client -// client.SetRootCertificateFromString("pem file content") -func (c *Client) SetRootCertificateFromString(pemContent string) *Client { - config, err := c.tlsConfig() - if err != nil { - c.log.Errorf("%v", err) - return c - } - if config.RootCAs == nil { - config.RootCAs = x509.NewCertPool() - } - - config.RootCAs.AppendCertsFromPEM([]byte(pemContent)) - return c -} - -// SetOutputDirectory method sets output directory for saving HTTP response into file. -// If the output directory not exists then resty creates one. This setting is optional one, -// if you're planning using absolute path in `Request.SetOutput` and can used together. -// client.SetOutputDirectory("/save/http/response/here") -func (c *Client) SetOutputDirectory(dirPath string) *Client { - c.outputDirectory = dirPath - return c -} - -// SetTransport method sets custom `*http.Transport` or any `http.RoundTripper` -// compatible interface implementation in the resty client. -// -// Note: -// -// - If transport is not type of `*http.Transport` then you may not be able to -// take advantage of some of the Resty client settings. -// -// - It overwrites the Resty client transport instance and it's configurations. -// -// transport := &http.Transport{ -// // somthing like Proxying to httptest.Server, etc... -// Proxy: func(req *http.Request) (*url.URL, error) { -// return url.Parse(server.URL) -// }, -// } -// -// client.SetTransport(transport) -func (c *Client) SetTransport(transport http.RoundTripper) *Client { - if transport != nil { - c.httpClient.Transport = transport - } - return c -} - -// SetScheme method sets custom scheme in the Resty client. It's way to override default. -// client.SetScheme("http") -func (c *Client) SetScheme(scheme string) *Client { - if !IsStringEmpty(scheme) { - c.scheme = strings.TrimSpace(scheme) - } - return c -} - -// SetCloseConnection method sets variable `Close` in http request struct with the given -// value. More info: https://golang.org/src/net/http/request.go -func (c *Client) SetCloseConnection(close bool) *Client { - c.closeConnection = close - return c -} - -// SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically. -// Resty exposes the raw response body as `io.ReadCloser`. Also do not forget to close the body, -// otherwise you might get into connection leaks, no connection reuse. -// -// Note: Response middlewares are not applicable, if you use this option. Basically you have -// taken over the control of response parsing from `Resty`. -func (c *Client) SetDoNotParseResponse(parse bool) *Client { - c.notParseResponse = parse - return c -} - -// SetPathParam method sets single URL path key-value pair in the -// Resty client instance. -// client.SetPathParam("userId", "sample@sample.com") -// -// Result: -// URL - /v1/users/{userId}/details -// Composed URL - /v1/users/sample@sample.com/details -// It replaces the value of the key while composing the request URL. -// -// Also it can be overridden at request level Path Params options, -// see `Request.SetPathParam` or `Request.SetPathParams`. -func (c *Client) SetPathParam(param, value string) *Client { - c.PathParams[param] = value - return c -} - -// SetPathParams method sets multiple URL path key-value pairs at one go in the -// Resty client instance. -// client.SetPathParams(map[string]string{ -// "userId": "sample@sample.com", -// "subAccountId": "100002", -// }) -// -// Result: -// URL - /v1/users/{userId}/{subAccountId}/details -// Composed URL - /v1/users/sample@sample.com/100002/details -// It replaces the value of the key while composing the request URL. -// -// Also it can be overridden at request level Path Params options, -// see `Request.SetPathParam` or `Request.SetPathParams`. -func (c *Client) SetPathParams(params map[string]string) *Client { - for p, v := range params { - c.SetPathParam(p, v) - } - return c -} - -// SetJSONEscapeHTML method is to enable/disable the HTML escape on JSON marshal. -// -// Note: This option only applicable to standard JSON Marshaller. -func (c *Client) SetJSONEscapeHTML(b bool) *Client { - c.jsonEscapeHTML = b - return c -} - -// EnableTrace method enables the Resty client trace for the requests fired from -// the client using `httptrace.ClientTrace` and provides insights. -// -// client := resty.New().EnableTrace() -// -// resp, err := client.R().Get("https://httpbin.org/get") -// fmt.Println("Error:", err) -// fmt.Println("Trace Info:", resp.Request.TraceInfo()) -// -// Also `Request.EnableTrace` available too to get trace info for single request. -// -// Since v2.0.0 -func (c *Client) EnableTrace() *Client { - c.trace = true - return c -} - -// DisableTrace method disables the Resty client trace. Refer to `Client.EnableTrace`. -// -// Since v2.0.0 -func (c *Client) DisableTrace() *Client { - c.trace = false - return c -} - -// IsProxySet method returns the true is proxy is set from resty client otherwise -// false. By default proxy is set from environment, refer to `http.ProxyFromEnvironment`. -func (c *Client) IsProxySet() bool { - return c.proxyURL != nil -} - -// GetClient method returns the current `http.Client` used by the resty client. -func (c *Client) GetClient() *http.Client { - return c.httpClient -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Client Unexported methods -//_______________________________________________________________________ - -// Executes method executes the given `Request` object and returns response -// error. -func (c *Client) execute(req *Request) (*Response, error) { - // Apply Request middleware - var err error - - // user defined on before request methods - // to modify the *resty.Request object - for _, f := range c.udBeforeRequest { - if err = f(c, req); err != nil { - return nil, wrapNoRetryErr(err) - } - } - - // resty middlewares - for _, f := range c.beforeRequest { - if err = f(c, req); err != nil { - return nil, wrapNoRetryErr(err) - } - } - - if hostHeader := req.Header.Get("Host"); hostHeader != "" { - req.RawRequest.Host = hostHeader - } - - // call pre-request if defined - if c.preReqHook != nil { - if err = c.preReqHook(c, req.RawRequest); err != nil { - return nil, wrapNoRetryErr(err) - } - } - - if err = requestLogger(c, req); err != nil { - return nil, wrapNoRetryErr(err) - } - - req.RawRequest.Body = newRequestBodyReleaser(req.RawRequest.Body, req.bodyBuf) - - req.Time = time.Now() - resp, err := c.httpClient.Do(req.RawRequest) - - response := &Response{ - Request: req, - RawResponse: resp, - } - - if err != nil || req.notParseResponse || c.notParseResponse { - response.setReceivedAt() - return response, err - } - - if !req.isSaveResponse { - defer closeq(resp.Body) - body := resp.Body - - // GitHub #142 & #187 - if strings.EqualFold(resp.Header.Get(hdrContentEncodingKey), "gzip") && resp.ContentLength != 0 { - if _, ok := body.(*gzip.Reader); !ok { - body, err = gzip.NewReader(body) - if err != nil { - response.setReceivedAt() - return response, err - } - defer closeq(body) - } - } - - if response.body, err = ioutil.ReadAll(body); err != nil { - response.setReceivedAt() - return response, err - } - - response.size = int64(len(response.body)) - } - - response.setReceivedAt() // after we read the body - - // Apply Response middleware - for _, f := range c.afterResponse { - if err = f(c, response); err != nil { - break - } - } - - return response, wrapNoRetryErr(err) -} - -// getting TLS client config if not exists then create one -func (c *Client) tlsConfig() (*tls.Config, error) { - transport, err := c.transport() - if err != nil { - return nil, err - } - if transport.TLSClientConfig == nil { - transport.TLSClientConfig = &tls.Config{} - } - return transport.TLSClientConfig, nil -} - -// Transport method returns `*http.Transport` currently in use or error -// in case currently used `transport` is not a `*http.Transport`. -func (c *Client) transport() (*http.Transport, error) { - if transport, ok := c.httpClient.Transport.(*http.Transport); ok { - return transport, nil - } - return nil, errors.New("current transport is not an *http.Transport instance") -} - -// just an internal helper method -func (c *Client) outputLogTo(w io.Writer) *Client { - c.log.(*logger).l.SetOutput(w) - return c -} - -// ResponseError is a wrapper for including the server response with an error. -// Neither the err nor the response should be nil. -type ResponseError struct { - Response *Response - Err error -} - -func (e *ResponseError) Error() string { - return e.Err.Error() -} - -func (e *ResponseError) Unwrap() error { - return e.Err -} - -// Helper to run onErrorHooks hooks. -// It wraps the error in a ResponseError if the resp is not nil -// so hooks can access it. -func (c *Client) onErrorHooks(req *Request, resp *Response, err error) { - if err != nil { - if resp != nil { // wrap with ResponseError - err = &ResponseError{Response: resp, Err: err} - } - for _, h := range c.errorHooks { - h(req, err) - } - } -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// File struct and its methods -//_______________________________________________________________________ - -// File struct represent file information for multipart request -type File struct { - Name string - ParamName string - io.Reader -} - -// String returns string value of current file details -func (f *File) String() string { - return fmt.Sprintf("ParamName: %v; FileName: %v", f.ParamName, f.Name) -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// MultipartField struct -//_______________________________________________________________________ - -// MultipartField struct represent custom data part for multipart request -type MultipartField struct { - Param string - FileName string - ContentType string - io.Reader -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Unexported package methods -//_______________________________________________________________________ - -func createClient(hc *http.Client) *Client { - if hc.Transport == nil { - hc.Transport = createTransport(nil) - } - - c := &Client{ // not setting lang default values - QueryParam: url.Values{}, - FormData: url.Values{}, - Header: http.Header{}, - Cookies: make([]*http.Cookie, 0), - RetryWaitTime: defaultWaitTime, - RetryMaxWaitTime: defaultMaxWaitTime, - PathParams: make(map[string]string), - JSONMarshal: json.Marshal, - JSONUnmarshal: json.Unmarshal, - XMLMarshal: xml.Marshal, - XMLUnmarshal: xml.Unmarshal, - HeaderAuthorizationKey: http.CanonicalHeaderKey("Authorization"), - - jsonEscapeHTML: true, - httpClient: hc, - debugBodySizeLimit: math.MaxInt32, - } - - // Logger - c.SetLogger(createLogger()) - - // default before request middlewares - c.beforeRequest = []RequestMiddleware{ - parseRequestURL, - parseRequestHeader, - parseRequestBody, - createHTTPRequest, - addCredentials, - } - - // user defined request middlewares - c.udBeforeRequest = []RequestMiddleware{} - - // default after response middlewares - c.afterResponse = []ResponseMiddleware{ - responseLogger, - parseResponseBody, - saveResponseIntoFile, - } - - return c -} diff --git a/vendor/github.com/go-resty/resty/v2/middleware.go b/vendor/github.com/go-resty/resty/v2/middleware.go deleted file mode 100644 index 0e8ac2b6..00000000 --- a/vendor/github.com/go-resty/resty/v2/middleware.go +++ /dev/null @@ -1,543 +0,0 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "bytes" - "errors" - "fmt" - "io" - "io/ioutil" - "mime/multipart" - "net/http" - "net/url" - "os" - "path/filepath" - "reflect" - "strings" - "time" -) - -const debugRequestLogKey = "__restyDebugRequestLog" - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Request Middleware(s) -//_______________________________________________________________________ - -func parseRequestURL(c *Client, r *Request) error { - // GitHub #103 Path Params - if len(r.PathParams) > 0 { - for p, v := range r.PathParams { - r.URL = strings.Replace(r.URL, "{"+p+"}", url.PathEscape(v), -1) - } - } - if len(c.PathParams) > 0 { - for p, v := range c.PathParams { - r.URL = strings.Replace(r.URL, "{"+p+"}", url.PathEscape(v), -1) - } - } - - // Parsing request URL - reqURL, err := url.Parse(r.URL) - if err != nil { - return err - } - - // If Request.URL is relative path then added c.HostURL into - // the request URL otherwise Request.URL will be used as-is - if !reqURL.IsAbs() { - r.URL = reqURL.String() - if len(r.URL) > 0 && r.URL[0] != '/' { - r.URL = "/" + r.URL - } - - reqURL, err = url.Parse(c.HostURL + r.URL) - if err != nil { - return err - } - } - - // GH #407 && #318 - if reqURL.Scheme == "" && len(c.scheme) > 0 { - reqURL.Scheme = c.scheme - } - - // Adding Query Param - query := make(url.Values) - for k, v := range c.QueryParam { - for _, iv := range v { - query.Add(k, iv) - } - } - - for k, v := range r.QueryParam { - // remove query param from client level by key - // since overrides happens for that key in the request - query.Del(k) - - for _, iv := range v { - query.Add(k, iv) - } - } - - // GitHub #123 Preserve query string order partially. - // Since not feasible in `SetQuery*` resty methods, because - // standard package `url.Encode(...)` sorts the query params - // alphabetically - if len(query) > 0 { - if IsStringEmpty(reqURL.RawQuery) { - reqURL.RawQuery = query.Encode() - } else { - reqURL.RawQuery = reqURL.RawQuery + "&" + query.Encode() - } - } - - r.URL = reqURL.String() - - return nil -} - -func parseRequestHeader(c *Client, r *Request) error { - hdr := make(http.Header) - for k := range c.Header { - hdr[k] = append(hdr[k], c.Header[k]...) - } - - for k := range r.Header { - hdr.Del(k) - hdr[k] = append(hdr[k], r.Header[k]...) - } - - if IsStringEmpty(hdr.Get(hdrUserAgentKey)) { - hdr.Set(hdrUserAgentKey, hdrUserAgentValue) - } - - ct := hdr.Get(hdrContentTypeKey) - if IsStringEmpty(hdr.Get(hdrAcceptKey)) && !IsStringEmpty(ct) && - (IsJSONType(ct) || IsXMLType(ct)) { - hdr.Set(hdrAcceptKey, hdr.Get(hdrContentTypeKey)) - } - - r.Header = hdr - - return nil -} - -func parseRequestBody(c *Client, r *Request) (err error) { - if isPayloadSupported(r.Method, c.AllowGetMethodPayload) { - // Handling Multipart - if r.isMultiPart && !(r.Method == MethodPatch) { - if err = handleMultipart(c, r); err != nil { - return - } - - goto CL - } - - // Handling Form Data - if len(c.FormData) > 0 || len(r.FormData) > 0 { - handleFormData(c, r) - - goto CL - } - - // Handling Request body - if r.Body != nil { - handleContentType(c, r) - - if err = handleRequestBody(c, r); err != nil { - return - } - } - } - -CL: - // by default resty won't set content length, you can if you want to :) - if (c.setContentLength || r.setContentLength) && r.bodyBuf != nil { - r.Header.Set(hdrContentLengthKey, fmt.Sprintf("%d", r.bodyBuf.Len())) - } - - return -} - -func createHTTPRequest(c *Client, r *Request) (err error) { - if r.bodyBuf == nil { - if reader, ok := r.Body.(io.Reader); ok { - r.RawRequest, err = http.NewRequest(r.Method, r.URL, reader) - } else if c.setContentLength || r.setContentLength { - r.RawRequest, err = http.NewRequest(r.Method, r.URL, http.NoBody) - } else { - r.RawRequest, err = http.NewRequest(r.Method, r.URL, nil) - } - } else { - r.RawRequest, err = http.NewRequest(r.Method, r.URL, r.bodyBuf) - } - - if err != nil { - return - } - - // Assign close connection option - r.RawRequest.Close = c.closeConnection - - // Add headers into http request - r.RawRequest.Header = r.Header - - // Add cookies from client instance into http request - for _, cookie := range c.Cookies { - r.RawRequest.AddCookie(cookie) - } - - // Add cookies from request instance into http request - for _, cookie := range r.Cookies { - r.RawRequest.AddCookie(cookie) - } - - // Enable trace - if c.trace || r.trace { - r.clientTrace = &clientTrace{} - r.ctx = r.clientTrace.createContext(r.Context()) - } - - // Use context if it was specified - if r.ctx != nil { - r.RawRequest = r.RawRequest.WithContext(r.ctx) - } - - bodyCopy, err := getBodyCopy(r) - if err != nil { - return err - } - - // assign get body func for the underlying raw request instance - r.RawRequest.GetBody = func() (io.ReadCloser, error) { - if bodyCopy != nil { - return ioutil.NopCloser(bytes.NewReader(bodyCopy.Bytes())), nil - } - return nil, nil - } - - return -} - -func addCredentials(c *Client, r *Request) error { - var isBasicAuth bool - // Basic Auth - if r.UserInfo != nil { // takes precedence - r.RawRequest.SetBasicAuth(r.UserInfo.Username, r.UserInfo.Password) - isBasicAuth = true - } else if c.UserInfo != nil { - r.RawRequest.SetBasicAuth(c.UserInfo.Username, c.UserInfo.Password) - isBasicAuth = true - } - - if !c.DisableWarn { - if isBasicAuth && !strings.HasPrefix(r.URL, "https") { - c.log.Warnf("Using Basic Auth in HTTP mode is not secure, use HTTPS") - } - } - - // Set the Authorization Header Scheme - var authScheme string - if !IsStringEmpty(r.AuthScheme) { - authScheme = r.AuthScheme - } else if !IsStringEmpty(c.AuthScheme) { - authScheme = c.AuthScheme - } else { - authScheme = "Bearer" - } - - // Build the Token Auth header - if !IsStringEmpty(r.Token) { // takes precedence - r.RawRequest.Header.Set(c.HeaderAuthorizationKey, authScheme+" "+r.Token) - } else if !IsStringEmpty(c.Token) { - r.RawRequest.Header.Set(c.HeaderAuthorizationKey, authScheme+" "+c.Token) - } - - return nil -} - -func requestLogger(c *Client, r *Request) error { - if c.Debug { - rr := r.RawRequest - rl := &RequestLog{Header: copyHeaders(rr.Header), Body: r.fmtBodyString(c.debugBodySizeLimit)} - if c.requestLog != nil { - if err := c.requestLog(rl); err != nil { - return err - } - } - // fmt.Sprintf("COOKIES:\n%s\n", composeCookies(c.GetClient().Jar, *rr.URL)) + - - reqLog := "\n==============================================================================\n" + - "~~~ REQUEST ~~~\n" + - fmt.Sprintf("%s %s %s\n", r.Method, rr.URL.RequestURI(), rr.Proto) + - fmt.Sprintf("HOST : %s\n", rr.URL.Host) + - fmt.Sprintf("HEADERS:\n%s\n", composeHeaders(c, r, rl.Header)) + - fmt.Sprintf("BODY :\n%v\n", rl.Body) + - "------------------------------------------------------------------------------\n" - - r.initValuesMap() - r.values[debugRequestLogKey] = reqLog - } - - return nil -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Response Middleware(s) -//_______________________________________________________________________ - -func responseLogger(c *Client, res *Response) error { - if c.Debug { - rl := &ResponseLog{Header: copyHeaders(res.Header()), Body: res.fmtBodyString(c.debugBodySizeLimit)} - if c.responseLog != nil { - if err := c.responseLog(rl); err != nil { - return err - } - } - - debugLog := res.Request.values[debugRequestLogKey].(string) - debugLog += "~~~ RESPONSE ~~~\n" + - fmt.Sprintf("STATUS : %s\n", res.Status()) + - fmt.Sprintf("PROTO : %s\n", res.RawResponse.Proto) + - fmt.Sprintf("RECEIVED AT : %v\n", res.ReceivedAt().Format(time.RFC3339Nano)) + - fmt.Sprintf("TIME DURATION: %v\n", res.Time()) + - "HEADERS :\n" + - composeHeaders(c, res.Request, rl.Header) + "\n" - if res.Request.isSaveResponse { - debugLog += "BODY :\n***** RESPONSE WRITTEN INTO FILE *****\n" - } else { - debugLog += fmt.Sprintf("BODY :\n%v\n", rl.Body) - } - debugLog += "==============================================================================\n" - - c.log.Debugf("%s", debugLog) - } - - return nil -} - -func parseResponseBody(c *Client, res *Response) (err error) { - if res.StatusCode() == http.StatusNoContent { - return - } - // Handles only JSON or XML content type - ct := firstNonEmpty(res.Request.forceContentType, res.Header().Get(hdrContentTypeKey), res.Request.fallbackContentType) - if IsJSONType(ct) || IsXMLType(ct) { - // HTTP status code > 199 and < 300, considered as Result - if res.IsSuccess() { - res.Request.Error = nil - if res.Request.Result != nil { - err = Unmarshalc(c, ct, res.body, res.Request.Result) - return - } - } - - // HTTP status code > 399, considered as Error - if res.IsError() { - // global error interface - if res.Request.Error == nil && c.Error != nil { - res.Request.Error = reflect.New(c.Error).Interface() - } - - if res.Request.Error != nil { - err = Unmarshalc(c, ct, res.body, res.Request.Error) - } - } - } - - return -} - -func handleMultipart(c *Client, r *Request) (err error) { - r.bodyBuf = acquireBuffer() - w := multipart.NewWriter(r.bodyBuf) - - for k, v := range c.FormData { - for _, iv := range v { - if err = w.WriteField(k, iv); err != nil { - return err - } - } - } - - for k, v := range r.FormData { - for _, iv := range v { - if strings.HasPrefix(k, "@") { // file - err = addFile(w, k[1:], iv) - if err != nil { - return - } - } else { // form value - if err = w.WriteField(k, iv); err != nil { - return err - } - } - } - } - - // #21 - adding io.Reader support - if len(r.multipartFiles) > 0 { - for _, f := range r.multipartFiles { - err = addFileReader(w, f) - if err != nil { - return - } - } - } - - // GitHub #130 adding multipart field support with content type - if len(r.multipartFields) > 0 { - for _, mf := range r.multipartFields { - if err = addMultipartFormField(w, mf); err != nil { - return - } - } - } - - r.Header.Set(hdrContentTypeKey, w.FormDataContentType()) - err = w.Close() - - return -} - -func handleFormData(c *Client, r *Request) { - formData := url.Values{} - - for k, v := range c.FormData { - for _, iv := range v { - formData.Add(k, iv) - } - } - - for k, v := range r.FormData { - // remove form data field from client level by key - // since overrides happens for that key in the request - formData.Del(k) - - for _, iv := range v { - formData.Add(k, iv) - } - } - - r.bodyBuf = bytes.NewBuffer([]byte(formData.Encode())) - r.Header.Set(hdrContentTypeKey, formContentType) - r.isFormData = true -} - -func handleContentType(c *Client, r *Request) { - contentType := r.Header.Get(hdrContentTypeKey) - if IsStringEmpty(contentType) { - contentType = DetectContentType(r.Body) - r.Header.Set(hdrContentTypeKey, contentType) - } -} - -func handleRequestBody(c *Client, r *Request) (err error) { - var bodyBytes []byte - contentType := r.Header.Get(hdrContentTypeKey) - kind := kindOf(r.Body) - r.bodyBuf = nil - - if reader, ok := r.Body.(io.Reader); ok { - if c.setContentLength || r.setContentLength { // keep backward compatibility - r.bodyBuf = acquireBuffer() - _, err = r.bodyBuf.ReadFrom(reader) - r.Body = nil - } else { - // Otherwise buffer less processing for `io.Reader`, sounds good. - return - } - } else if b, ok := r.Body.([]byte); ok { - bodyBytes = b - } else if s, ok := r.Body.(string); ok { - bodyBytes = []byte(s) - } else if IsJSONType(contentType) && - (kind == reflect.Struct || kind == reflect.Map || kind == reflect.Slice) { - r.bodyBuf, err = jsonMarshal(c, r, r.Body) - if err != nil { - return - } - } else if IsXMLType(contentType) && (kind == reflect.Struct) { - bodyBytes, err = c.XMLMarshal(r.Body) - if err != nil { - return - } - } - - if bodyBytes == nil && r.bodyBuf == nil { - err = errors.New("unsupported 'Body' type/value") - } - - // if any errors during body bytes handling, return it - if err != nil { - return - } - - // []byte into Buffer - if bodyBytes != nil && r.bodyBuf == nil { - r.bodyBuf = acquireBuffer() - _, _ = r.bodyBuf.Write(bodyBytes) - } - - return -} - -func saveResponseIntoFile(c *Client, res *Response) error { - if res.Request.isSaveResponse { - file := "" - - if len(c.outputDirectory) > 0 && !filepath.IsAbs(res.Request.outputFile) { - file += c.outputDirectory + string(filepath.Separator) - } - - file = filepath.Clean(file + res.Request.outputFile) - if err := createDirectory(filepath.Dir(file)); err != nil { - return err - } - - outFile, err := os.Create(file) - if err != nil { - return err - } - defer closeq(outFile) - - // io.Copy reads maximum 32kb size, it is perfect for large file download too - defer closeq(res.RawResponse.Body) - - written, err := io.Copy(outFile, res.RawResponse.Body) - if err != nil { - return err - } - - res.size = written - } - - return nil -} - -func getBodyCopy(r *Request) (*bytes.Buffer, error) { - // If r.bodyBuf present, return the copy - if r.bodyBuf != nil { - return bytes.NewBuffer(r.bodyBuf.Bytes()), nil - } - - // Maybe body is `io.Reader`. - // Note: Resty user have to watchout for large body size of `io.Reader` - if r.RawRequest.Body != nil { - b, err := ioutil.ReadAll(r.RawRequest.Body) - if err != nil { - return nil, err - } - - // Restore the Body - closeq(r.RawRequest.Body) - r.RawRequest.Body = ioutil.NopCloser(bytes.NewBuffer(b)) - - // Return the Body bytes - return bytes.NewBuffer(b), nil - } - return nil, nil -} diff --git a/vendor/github.com/go-resty/resty/v2/redirect.go b/vendor/github.com/go-resty/resty/v2/redirect.go deleted file mode 100644 index 7d7e43bc..00000000 --- a/vendor/github.com/go-resty/resty/v2/redirect.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "errors" - "fmt" - "net" - "net/http" - "strings" -) - -type ( - // RedirectPolicy to regulate the redirects in the resty client. - // Objects implementing the RedirectPolicy interface can be registered as - // - // Apply function should return nil to continue the redirect jounery, otherwise - // return error to stop the redirect. - RedirectPolicy interface { - Apply(req *http.Request, via []*http.Request) error - } - - // The RedirectPolicyFunc type is an adapter to allow the use of ordinary functions as RedirectPolicy. - // If f is a function with the appropriate signature, RedirectPolicyFunc(f) is a RedirectPolicy object that calls f. - RedirectPolicyFunc func(*http.Request, []*http.Request) error -) - -// Apply calls f(req, via). -func (f RedirectPolicyFunc) Apply(req *http.Request, via []*http.Request) error { - return f(req, via) -} - -// NoRedirectPolicy is used to disable redirects in the HTTP client -// resty.SetRedirectPolicy(NoRedirectPolicy()) -func NoRedirectPolicy() RedirectPolicy { - return RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error { - return errors.New("auto redirect is disabled") - }) -} - -// FlexibleRedirectPolicy is convenient method to create No of redirect policy for HTTP client. -// resty.SetRedirectPolicy(FlexibleRedirectPolicy(20)) -func FlexibleRedirectPolicy(noOfRedirect int) RedirectPolicy { - return RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error { - if len(via) >= noOfRedirect { - return fmt.Errorf("stopped after %d redirects", noOfRedirect) - } - checkHostAndAddHeaders(req, via[0]) - return nil - }) -} - -// DomainCheckRedirectPolicy is convenient method to define domain name redirect rule in resty client. -// Redirect is allowed for only mentioned host in the policy. -// resty.SetRedirectPolicy(DomainCheckRedirectPolicy("host1.com", "host2.org", "host3.net")) -func DomainCheckRedirectPolicy(hostnames ...string) RedirectPolicy { - hosts := make(map[string]bool) - for _, h := range hostnames { - hosts[strings.ToLower(h)] = true - } - - fn := RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error { - if ok := hosts[getHostname(req.URL.Host)]; !ok { - return errors.New("redirect is not allowed as per DomainCheckRedirectPolicy") - } - - return nil - }) - - return fn -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Package Unexported methods -//_______________________________________________________________________ - -func getHostname(host string) (hostname string) { - if strings.Index(host, ":") > 0 { - host, _, _ = net.SplitHostPort(host) - } - hostname = strings.ToLower(host) - return -} - -// By default Golang will not redirect request headers -// after go throughing various discussion comments from thread -// https://github.com/golang/go/issues/4800 -// Resty will add all the headers during a redirect for the same host -func checkHostAndAddHeaders(cur *http.Request, pre *http.Request) { - curHostname := getHostname(cur.URL.Host) - preHostname := getHostname(pre.URL.Host) - if strings.EqualFold(curHostname, preHostname) { - for key, val := range pre.Header { - cur.Header[key] = val - } - } else { // only library User-Agent header is added - cur.Header.Set(hdrUserAgentKey, hdrUserAgentValue) - } -} diff --git a/vendor/github.com/go-resty/resty/v2/request.go b/vendor/github.com/go-resty/resty/v2/request.go deleted file mode 100644 index 672df88c..00000000 --- a/vendor/github.com/go-resty/resty/v2/request.go +++ /dev/null @@ -1,896 +0,0 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "bytes" - "context" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "net" - "net/http" - "net/url" - "reflect" - "strings" - "time" -) - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Request struct and methods -//_______________________________________________________________________ - -// Request struct is used to compose and fire individual request from -// resty client. Request provides an options to override client level -// settings and also an options for the request composition. -type Request struct { - URL string - Method string - Token string - AuthScheme string - QueryParam url.Values - FormData url.Values - PathParams map[string]string - Header http.Header - Time time.Time - Body interface{} - Result interface{} - Error interface{} - RawRequest *http.Request - SRV *SRVRecord - UserInfo *User - Cookies []*http.Cookie - - // Attempt is to represent the request attempt made during a Resty - // request execution flow, including retry count. - // - // Since v2.4.0 - Attempt int - - isMultiPart bool - isFormData bool - setContentLength bool - isSaveResponse bool - notParseResponse bool - jsonEscapeHTML bool - trace bool - outputFile string - fallbackContentType string - forceContentType string - ctx context.Context - values map[string]interface{} - client *Client - bodyBuf *bytes.Buffer - clientTrace *clientTrace - multipartFiles []*File - multipartFields []*MultipartField - retryConditions []RetryConditionFunc -} - -// Context method returns the Context if its already set in request -// otherwise it creates new one using `context.Background()`. -func (r *Request) Context() context.Context { - if r.ctx == nil { - return context.Background() - } - return r.ctx -} - -// SetContext method sets the context.Context for current Request. It allows -// to interrupt the request execution if ctx.Done() channel is closed. -// See https://blog.golang.org/context article and the "context" package -// documentation. -func (r *Request) SetContext(ctx context.Context) *Request { - r.ctx = ctx - return r -} - -// SetHeader method is to set a single header field and its value in the current request. -// -// For Example: To set `Content-Type` and `Accept` as `application/json`. -// client.R(). -// SetHeader("Content-Type", "application/json"). -// SetHeader("Accept", "application/json") -// -// Also you can override header value, which was set at client instance level. -func (r *Request) SetHeader(header, value string) *Request { - r.Header.Set(header, value) - return r -} - -// SetHeaders method sets multiple headers field and its values at one go in the current request. -// -// For Example: To set `Content-Type` and `Accept` as `application/json` -// -// client.R(). -// SetHeaders(map[string]string{ -// "Content-Type": "application/json", -// "Accept": "application/json", -// }) -// Also you can override header value, which was set at client instance level. -func (r *Request) SetHeaders(headers map[string]string) *Request { - for h, v := range headers { - r.SetHeader(h, v) - } - return r -} - -// SetHeaderMultiValues sets multiple headers fields and its values is list of strings at one go in the current request. -// -// For Example: To set `Accept` as `text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, */*;q=0.8` -// -// client.R(). -// SetHeaderMultiValues(map[string][]string{ -// "Accept": []string{"text/html", "application/xhtml+xml", "application/xml;q=0.9", "image/webp", "*/*;q=0.8"}, -// }) -// Also you can override header value, which was set at client instance level. -func (r *Request) SetHeaderMultiValues(headers map[string][]string) *Request { - for key, values := range headers { - r.SetHeader(key, strings.Join(values, ", ")) - } - return r -} - -// SetHeaderVerbatim method is to set a single header field and its value verbatim in the current request. -// -// For Example: To set `all_lowercase` and `UPPERCASE` as `available`. -// client.R(). -// SetHeaderVerbatim("all_lowercase", "available"). -// SetHeaderVerbatim("UPPERCASE", "available") -// -// Also you can override header value, which was set at client instance level. -// -// Since v2.6.0 -func (r *Request) SetHeaderVerbatim(header, value string) *Request { - r.Header[header] = []string{value} - return r -} - -// SetQueryParam method sets single parameter and its value in the current request. -// It will be formed as query string for the request. -// -// For Example: `search=kitchen%20papers&size=large` in the URL after `?` mark. -// client.R(). -// SetQueryParam("search", "kitchen papers"). -// SetQueryParam("size", "large") -// Also you can override query params value, which was set at client instance level. -func (r *Request) SetQueryParam(param, value string) *Request { - r.QueryParam.Set(param, value) - return r -} - -// SetQueryParams method sets multiple parameters and its values at one go in the current request. -// It will be formed as query string for the request. -// -// For Example: `search=kitchen%20papers&size=large` in the URL after `?` mark. -// client.R(). -// SetQueryParams(map[string]string{ -// "search": "kitchen papers", -// "size": "large", -// }) -// Also you can override query params value, which was set at client instance level. -func (r *Request) SetQueryParams(params map[string]string) *Request { - for p, v := range params { - r.SetQueryParam(p, v) - } - return r -} - -// SetQueryParamsFromValues method appends multiple parameters with multi-value -// (`url.Values`) at one go in the current request. It will be formed as -// query string for the request. -// -// For Example: `status=pending&status=approved&status=open` in the URL after `?` mark. -// client.R(). -// SetQueryParamsFromValues(url.Values{ -// "status": []string{"pending", "approved", "open"}, -// }) -// Also you can override query params value, which was set at client instance level. -func (r *Request) SetQueryParamsFromValues(params url.Values) *Request { - for p, v := range params { - for _, pv := range v { - r.QueryParam.Add(p, pv) - } - } - return r -} - -// SetQueryString method provides ability to use string as an input to set URL query string for the request. -// -// Using String as an input -// client.R(). -// SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more") -func (r *Request) SetQueryString(query string) *Request { - params, err := url.ParseQuery(strings.TrimSpace(query)) - if err == nil { - for p, v := range params { - for _, pv := range v { - r.QueryParam.Add(p, pv) - } - } - } else { - r.client.log.Errorf("%v", err) - } - return r -} - -// SetFormData method sets Form parameters and their values in the current request. -// It's applicable only HTTP method `POST` and `PUT` and requests content type would be set as -// `application/x-www-form-urlencoded`. -// client.R(). -// SetFormData(map[string]string{ -// "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F", -// "user_id": "3455454545", -// }) -// Also you can override form data value, which was set at client instance level. -func (r *Request) SetFormData(data map[string]string) *Request { - for k, v := range data { - r.FormData.Set(k, v) - } - return r -} - -// SetFormDataFromValues method appends multiple form parameters with multi-value -// (`url.Values`) at one go in the current request. -// client.R(). -// SetFormDataFromValues(url.Values{ -// "search_criteria": []string{"book", "glass", "pencil"}, -// }) -// Also you can override form data value, which was set at client instance level. -func (r *Request) SetFormDataFromValues(data url.Values) *Request { - for k, v := range data { - for _, kv := range v { - r.FormData.Add(k, kv) - } - } - return r -} - -// SetBody method sets the request body for the request. It supports various realtime needs as easy. -// We can say its quite handy or powerful. Supported request body data types is `string`, -// `[]byte`, `struct`, `map`, `slice` and `io.Reader`. Body value can be pointer or non-pointer. -// Automatic marshalling for JSON and XML content type, if it is `struct`, `map`, or `slice`. -// -// Note: `io.Reader` is processed as bufferless mode while sending request. -// -// For Example: Struct as a body input, based on content type, it will be marshalled. -// client.R(). -// SetBody(User{ -// Username: "jeeva@myjeeva.com", -// Password: "welcome2resty", -// }) -// -// Map as a body input, based on content type, it will be marshalled. -// client.R(). -// SetBody(map[string]interface{}{ -// "username": "jeeva@myjeeva.com", -// "password": "welcome2resty", -// "address": &Address{ -// Address1: "1111 This is my street", -// Address2: "Apt 201", -// City: "My City", -// State: "My State", -// ZipCode: 00000, -// }, -// }) -// -// String as a body input. Suitable for any need as a string input. -// client.R(). -// SetBody(`{ -// "username": "jeeva@getrightcare.com", -// "password": "admin" -// }`) -// -// []byte as a body input. Suitable for raw request such as file upload, serialize & deserialize, etc. -// client.R(). -// SetBody([]byte("This is my raw request, sent as-is")) -func (r *Request) SetBody(body interface{}) *Request { - r.Body = body - return r -} - -// SetResult method is to register the response `Result` object for automatic unmarshalling for the request, -// if response status code is between 200 and 299 and content type either JSON or XML. -// -// Note: Result object can be pointer or non-pointer. -// client.R().SetResult(&AuthToken{}) -// // OR -// client.R().SetResult(AuthToken{}) -// -// Accessing a result value from response instance. -// response.Result().(*AuthToken) -func (r *Request) SetResult(res interface{}) *Request { - r.Result = getPointer(res) - return r -} - -// SetError method is to register the request `Error` object for automatic unmarshalling for the request, -// if response status code is greater than 399 and content type either JSON or XML. -// -// Note: Error object can be pointer or non-pointer. -// client.R().SetError(&AuthError{}) -// // OR -// client.R().SetError(AuthError{}) -// -// Accessing a error value from response instance. -// response.Error().(*AuthError) -func (r *Request) SetError(err interface{}) *Request { - r.Error = getPointer(err) - return r -} - -// SetFile method is to set single file field name and its path for multipart upload. -// client.R(). -// SetFile("my_file", "/Users/jeeva/Gas Bill - Sep.pdf") -func (r *Request) SetFile(param, filePath string) *Request { - r.isMultiPart = true - r.FormData.Set("@"+param, filePath) - return r -} - -// SetFiles method is to set multiple file field name and its path for multipart upload. -// client.R(). -// SetFiles(map[string]string{ -// "my_file1": "/Users/jeeva/Gas Bill - Sep.pdf", -// "my_file2": "/Users/jeeva/Electricity Bill - Sep.pdf", -// "my_file3": "/Users/jeeva/Water Bill - Sep.pdf", -// }) -func (r *Request) SetFiles(files map[string]string) *Request { - r.isMultiPart = true - for f, fp := range files { - r.FormData.Set("@"+f, fp) - } - return r -} - -// SetFileReader method is to set single file using io.Reader for multipart upload. -// client.R(). -// SetFileReader("profile_img", "my-profile-img.png", bytes.NewReader(profileImgBytes)). -// SetFileReader("notes", "user-notes.txt", bytes.NewReader(notesBytes)) -func (r *Request) SetFileReader(param, fileName string, reader io.Reader) *Request { - r.isMultiPart = true - r.multipartFiles = append(r.multipartFiles, &File{ - Name: fileName, - ParamName: param, - Reader: reader, - }) - return r -} - -// SetMultipartFormData method allows simple form data to be attached to the request as `multipart:form-data` -func (r *Request) SetMultipartFormData(data map[string]string) *Request { - for k, v := range data { - r = r.SetMultipartField(k, "", "", strings.NewReader(v)) - } - - return r -} - -// SetMultipartField method is to set custom data using io.Reader for multipart upload. -func (r *Request) SetMultipartField(param, fileName, contentType string, reader io.Reader) *Request { - r.isMultiPart = true - r.multipartFields = append(r.multipartFields, &MultipartField{ - Param: param, - FileName: fileName, - ContentType: contentType, - Reader: reader, - }) - return r -} - -// SetMultipartFields method is to set multiple data fields using io.Reader for multipart upload. -// -// For Example: -// client.R().SetMultipartFields( -// &resty.MultipartField{ -// Param: "uploadManifest1", -// FileName: "upload-file-1.json", -// ContentType: "application/json", -// Reader: strings.NewReader(`{"input": {"name": "Uploaded document 1", "_filename" : ["file1.txt"]}}`), -// }, -// &resty.MultipartField{ -// Param: "uploadManifest2", -// FileName: "upload-file-2.json", -// ContentType: "application/json", -// Reader: strings.NewReader(`{"input": {"name": "Uploaded document 2", "_filename" : ["file2.txt"]}}`), -// }) -// -// If you have slice already, then simply call- -// client.R().SetMultipartFields(fields...) -func (r *Request) SetMultipartFields(fields ...*MultipartField) *Request { - r.isMultiPart = true - r.multipartFields = append(r.multipartFields, fields...) - return r -} - -// SetContentLength method sets the HTTP header `Content-Length` value for current request. -// By default Resty won't set `Content-Length`. Also you have an option to enable for every -// request. -// -// See `Client.SetContentLength` -// client.R().SetContentLength(true) -func (r *Request) SetContentLength(l bool) *Request { - r.setContentLength = l - return r -} - -// SetBasicAuth method sets the basic authentication header in the current HTTP request. -// -// For Example: -// Authorization: Basic -// -// To set the header for username "go-resty" and password "welcome" -// client.R().SetBasicAuth("go-resty", "welcome") -// -// This method overrides the credentials set by method `Client.SetBasicAuth`. -func (r *Request) SetBasicAuth(username, password string) *Request { - r.UserInfo = &User{Username: username, Password: password} - return r -} - -// SetAuthToken method sets the auth token header(Default Scheme: Bearer) in the current HTTP request. Header example: -// Authorization: Bearer -// -// For Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F -// -// client.R().SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F") -// -// This method overrides the Auth token set by method `Client.SetAuthToken`. -func (r *Request) SetAuthToken(token string) *Request { - r.Token = token - return r -} - -// SetAuthScheme method sets the auth token scheme type in the HTTP request. For Example: -// Authorization: -// -// For Example: To set the scheme to use OAuth -// -// client.R().SetAuthScheme("OAuth") -// -// This auth header scheme gets added to all the request rasied from this client instance. -// Also it can be overridden or set one at the request level is supported. -// -// Information about Auth schemes can be found in RFC7235 which is linked to below along with the page containing -// the currently defined official authentication schemes: -// https://tools.ietf.org/html/rfc7235 -// https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes -// -// This method overrides the Authorization scheme set by method `Client.SetAuthScheme`. -func (r *Request) SetAuthScheme(scheme string) *Request { - r.AuthScheme = scheme - return r -} - -// SetOutput method sets the output file for current HTTP request. Current HTTP response will be -// saved into given file. It is similar to `curl -o` flag. Absolute path or relative path can be used. -// If is it relative path then output file goes under the output directory, as mentioned -// in the `Client.SetOutputDirectory`. -// client.R(). -// SetOutput("/Users/jeeva/Downloads/ReplyWithHeader-v5.1-beta.zip"). -// Get("http://bit.ly/1LouEKr") -// -// Note: In this scenario `Response.Body` might be nil. -func (r *Request) SetOutput(file string) *Request { - r.outputFile = file - r.isSaveResponse = true - return r -} - -// SetSRV method sets the details to query the service SRV record and execute the -// request. -// client.R(). -// SetSRV(SRVRecord{"web", "testservice.com"}). -// Get("/get") -func (r *Request) SetSRV(srv *SRVRecord) *Request { - r.SRV = srv - return r -} - -// SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically. -// Resty exposes the raw response body as `io.ReadCloser`. Also do not forget to close the body, -// otherwise you might get into connection leaks, no connection reuse. -// -// Note: Response middlewares are not applicable, if you use this option. Basically you have -// taken over the control of response parsing from `Resty`. -func (r *Request) SetDoNotParseResponse(parse bool) *Request { - r.notParseResponse = parse - return r -} - -// SetPathParam method sets single URL path key-value pair in the -// Resty current request instance. -// client.R().SetPathParam("userId", "sample@sample.com") -// -// Result: -// URL - /v1/users/{userId}/details -// Composed URL - /v1/users/sample@sample.com/details -// It replaces the value of the key while composing the request URL. Also you can -// override Path Params value, which was set at client instance level. -func (r *Request) SetPathParam(param, value string) *Request { - r.PathParams[param] = value - return r -} - -// SetPathParams method sets multiple URL path key-value pairs at one go in the -// Resty current request instance. -// client.R().SetPathParams(map[string]string{ -// "userId": "sample@sample.com", -// "subAccountId": "100002", -// }) -// -// Result: -// URL - /v1/users/{userId}/{subAccountId}/details -// Composed URL - /v1/users/sample@sample.com/100002/details -// It replaces the value of the key while composing request URL. Also you can -// override Path Params value, which was set at client instance level. -func (r *Request) SetPathParams(params map[string]string) *Request { - for p, v := range params { - r.SetPathParam(p, v) - } - return r -} - -// ExpectContentType method allows to provide fallback `Content-Type` for automatic unmarshalling -// when `Content-Type` response header is unavailable. -func (r *Request) ExpectContentType(contentType string) *Request { - r.fallbackContentType = contentType - return r -} - -// ForceContentType method provides a strong sense of response `Content-Type` for automatic unmarshalling. -// Resty gives this a higher priority than the `Content-Type` response header. This means that if both -// `Request.ForceContentType` is set and the response `Content-Type` is available, `ForceContentType` will win. -func (r *Request) ForceContentType(contentType string) *Request { - r.forceContentType = contentType - return r -} - -// SetJSONEscapeHTML method is to enable/disable the HTML escape on JSON marshal. -// -// Note: This option only applicable to standard JSON Marshaller. -func (r *Request) SetJSONEscapeHTML(b bool) *Request { - r.jsonEscapeHTML = b - return r -} - -// SetCookie method appends a single cookie in the current request instance. -// client.R().SetCookie(&http.Cookie{ -// Name:"go-resty", -// Value:"This is cookie value", -// }) -// -// Note: Method appends the Cookie value into existing Cookie if already existing. -// -// Since v2.1.0 -func (r *Request) SetCookie(hc *http.Cookie) *Request { - r.Cookies = append(r.Cookies, hc) - return r -} - -// SetCookies method sets an array of cookies in the current request instance. -// cookies := []*http.Cookie{ -// &http.Cookie{ -// Name:"go-resty-1", -// Value:"This is cookie 1 value", -// }, -// &http.Cookie{ -// Name:"go-resty-2", -// Value:"This is cookie 2 value", -// }, -// } -// -// // Setting a cookies into resty's current request -// client.R().SetCookies(cookies) -// -// Note: Method appends the Cookie value into existing Cookie if already existing. -// -// Since v2.1.0 -func (r *Request) SetCookies(rs []*http.Cookie) *Request { - r.Cookies = append(r.Cookies, rs...) - return r -} - -// AddRetryCondition method adds a retry condition function to the request's -// array of functions that are checked to determine if the request is retried. -// The request will retry if any of the functions return true and error is nil. -// -// Note: These retry conditions are checked before all retry conditions of the client. -// -// Since v2.7.0 -func (r *Request) AddRetryCondition(condition RetryConditionFunc) *Request { - r.retryConditions = append(r.retryConditions, condition) - return r -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// HTTP request tracing -//_______________________________________________________________________ - -// EnableTrace method enables trace for the current request -// using `httptrace.ClientTrace` and provides insights. -// -// client := resty.New() -// -// resp, err := client.R().EnableTrace().Get("https://httpbin.org/get") -// fmt.Println("Error:", err) -// fmt.Println("Trace Info:", resp.Request.TraceInfo()) -// -// See `Client.EnableTrace` available too to get trace info for all requests. -// -// Since v2.0.0 -func (r *Request) EnableTrace() *Request { - r.trace = true - return r -} - -// TraceInfo method returns the trace info for the request. -// If either the Client or Request EnableTrace function has not been called -// prior to the request being made, an empty TraceInfo object will be returned. -// -// Since v2.0.0 -func (r *Request) TraceInfo() TraceInfo { - ct := r.clientTrace - - if ct == nil { - return TraceInfo{} - } - - ti := TraceInfo{ - DNSLookup: ct.dnsDone.Sub(ct.dnsStart), - TLSHandshake: ct.tlsHandshakeDone.Sub(ct.tlsHandshakeStart), - ServerTime: ct.gotFirstResponseByte.Sub(ct.gotConn), - IsConnReused: ct.gotConnInfo.Reused, - IsConnWasIdle: ct.gotConnInfo.WasIdle, - ConnIdleTime: ct.gotConnInfo.IdleTime, - RequestAttempt: r.Attempt, - } - - // Calculate the total time accordingly, - // when connection is reused - if ct.gotConnInfo.Reused { - ti.TotalTime = ct.endTime.Sub(ct.getConn) - } else { - ti.TotalTime = ct.endTime.Sub(ct.dnsStart) - } - - // Only calculate on successful connections - if !ct.connectDone.IsZero() { - ti.TCPConnTime = ct.connectDone.Sub(ct.dnsDone) - } - - // Only calculate on successful connections - if !ct.gotConn.IsZero() { - ti.ConnTime = ct.gotConn.Sub(ct.getConn) - } - - // Only calculate on successful connections - if !ct.gotFirstResponseByte.IsZero() { - ti.ResponseTime = ct.endTime.Sub(ct.gotFirstResponseByte) - } - - // Capture remote address info when connection is non-nil - if ct.gotConnInfo.Conn != nil { - ti.RemoteAddr = ct.gotConnInfo.Conn.RemoteAddr() - } - - return ti -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// HTTP verb method starts here -//_______________________________________________________________________ - -// Get method does GET HTTP request. It's defined in section 4.3.1 of RFC7231. -func (r *Request) Get(url string) (*Response, error) { - return r.Execute(MethodGet, url) -} - -// Head method does HEAD HTTP request. It's defined in section 4.3.2 of RFC7231. -func (r *Request) Head(url string) (*Response, error) { - return r.Execute(MethodHead, url) -} - -// Post method does POST HTTP request. It's defined in section 4.3.3 of RFC7231. -func (r *Request) Post(url string) (*Response, error) { - return r.Execute(MethodPost, url) -} - -// Put method does PUT HTTP request. It's defined in section 4.3.4 of RFC7231. -func (r *Request) Put(url string) (*Response, error) { - return r.Execute(MethodPut, url) -} - -// Delete method does DELETE HTTP request. It's defined in section 4.3.5 of RFC7231. -func (r *Request) Delete(url string) (*Response, error) { - return r.Execute(MethodDelete, url) -} - -// Options method does OPTIONS HTTP request. It's defined in section 4.3.7 of RFC7231. -func (r *Request) Options(url string) (*Response, error) { - return r.Execute(MethodOptions, url) -} - -// Patch method does PATCH HTTP request. It's defined in section 2 of RFC5789. -func (r *Request) Patch(url string) (*Response, error) { - return r.Execute(MethodPatch, url) -} - -// Send method performs the HTTP request using the method and URL already defined -// for current `Request`. -// req := client.R() -// req.Method = resty.GET -// req.URL = "http://httpbin.org/get" -// resp, err := client.R().Send() -func (r *Request) Send() (*Response, error) { - return r.Execute(r.Method, r.URL) -} - -// Execute method performs the HTTP request with given HTTP method and URL -// for current `Request`. -// resp, err := client.R().Execute(resty.GET, "http://httpbin.org/get") -func (r *Request) Execute(method, url string) (*Response, error) { - var addrs []*net.SRV - var resp *Response - var err error - - if r.isMultiPart && !(method == MethodPost || method == MethodPut || method == MethodPatch) { - // No OnError hook here since this is a request validation error - return nil, fmt.Errorf("multipart content is not allowed in HTTP verb [%v]", method) - } - - if r.SRV != nil { - _, addrs, err = net.LookupSRV(r.SRV.Service, "tcp", r.SRV.Domain) - if err != nil { - r.client.onErrorHooks(r, nil, err) - return nil, err - } - } - - r.Method = method - r.URL = r.selectAddr(addrs, url, 0) - - if r.client.RetryCount == 0 { - r.Attempt = 1 - resp, err = r.client.execute(r) - r.client.onErrorHooks(r, resp, unwrapNoRetryErr(err)) - return resp, unwrapNoRetryErr(err) - } - - err = Backoff( - func() (*Response, error) { - r.Attempt++ - - r.URL = r.selectAddr(addrs, url, r.Attempt) - - resp, err = r.client.execute(r) - if err != nil { - r.client.log.Errorf("%v, Attempt %v", err, r.Attempt) - } - - return resp, err - }, - Retries(r.client.RetryCount), - WaitTime(r.client.RetryWaitTime), - MaxWaitTime(r.client.RetryMaxWaitTime), - RetryConditions(append(r.retryConditions, r.client.RetryConditions...)), - RetryHooks(r.client.RetryHooks), - ) - - r.client.onErrorHooks(r, resp, unwrapNoRetryErr(err)) - - return resp, unwrapNoRetryErr(err) -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// SRVRecord struct -//_______________________________________________________________________ - -// SRVRecord struct holds the data to query the SRV record for the -// following service. -type SRVRecord struct { - Service string - Domain string -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Request Unexported methods -//_______________________________________________________________________ - -func (r *Request) fmtBodyString(sl int64) (body string) { - body = "***** NO CONTENT *****" - if !isPayloadSupported(r.Method, r.client.AllowGetMethodPayload) { - return - } - - if _, ok := r.Body.(io.Reader); ok { - body = "***** BODY IS io.Reader *****" - return - } - - // multipart or form-data - if r.isMultiPart || r.isFormData { - bodySize := int64(r.bodyBuf.Len()) - if bodySize > sl { - body = fmt.Sprintf("***** REQUEST TOO LARGE (size - %d) *****", bodySize) - return - } - body = r.bodyBuf.String() - return - } - - // request body data - if r.Body == nil { - return - } - var prtBodyBytes []byte - var err error - - contentType := r.Header.Get(hdrContentTypeKey) - kind := kindOf(r.Body) - if canJSONMarshal(contentType, kind) { - prtBodyBytes, err = json.MarshalIndent(&r.Body, "", " ") - } else if IsXMLType(contentType) && (kind == reflect.Struct) { - prtBodyBytes, err = xml.MarshalIndent(&r.Body, "", " ") - } else if b, ok := r.Body.(string); ok { - if IsJSONType(contentType) { - bodyBytes := []byte(b) - out := acquireBuffer() - defer releaseBuffer(out) - if err = json.Indent(out, bodyBytes, "", " "); err == nil { - prtBodyBytes = out.Bytes() - } - } else { - body = b - } - } else if b, ok := r.Body.([]byte); ok { - body = fmt.Sprintf("***** BODY IS byte(s) (size - %d) *****", len(b)) - return - } - - if prtBodyBytes != nil && err == nil { - body = string(prtBodyBytes) - } - - if len(body) > 0 { - bodySize := int64(len([]byte(body))) - if bodySize > sl { - body = fmt.Sprintf("***** REQUEST TOO LARGE (size - %d) *****", bodySize) - } - } - - return -} - -func (r *Request) selectAddr(addrs []*net.SRV, path string, attempt int) string { - if addrs == nil { - return path - } - - idx := attempt % len(addrs) - domain := strings.TrimRight(addrs[idx].Target, ".") - path = strings.TrimLeft(path, "/") - - return fmt.Sprintf("%s://%s:%d/%s", r.client.scheme, domain, addrs[idx].Port, path) -} - -func (r *Request) initValuesMap() { - if r.values == nil { - r.values = make(map[string]interface{}) - } -} - -var noescapeJSONMarshal = func(v interface{}) (*bytes.Buffer, error) { - buf := acquireBuffer() - encoder := json.NewEncoder(buf) - encoder.SetEscapeHTML(false) - if err := encoder.Encode(v); err != nil { - releaseBuffer(buf) - return nil, err - } - - return buf, nil -} diff --git a/vendor/github.com/go-resty/resty/v2/response.go b/vendor/github.com/go-resty/resty/v2/response.go deleted file mode 100644 index 8ae0e10b..00000000 --- a/vendor/github.com/go-resty/resty/v2/response.go +++ /dev/null @@ -1,175 +0,0 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "strings" - "time" -) - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Response struct and methods -//_______________________________________________________________________ - -// Response struct holds response values of executed request. -type Response struct { - Request *Request - RawResponse *http.Response - - body []byte - size int64 - receivedAt time.Time -} - -// Body method returns HTTP response as []byte array for the executed request. -// -// Note: `Response.Body` might be nil, if `Request.SetOutput` is used. -func (r *Response) Body() []byte { - if r.RawResponse == nil { - return []byte{} - } - return r.body -} - -// Status method returns the HTTP status string for the executed request. -// Example: 200 OK -func (r *Response) Status() string { - if r.RawResponse == nil { - return "" - } - return r.RawResponse.Status -} - -// StatusCode method returns the HTTP status code for the executed request. -// Example: 200 -func (r *Response) StatusCode() int { - if r.RawResponse == nil { - return 0 - } - return r.RawResponse.StatusCode -} - -// Proto method returns the HTTP response protocol used for the request. -func (r *Response) Proto() string { - if r.RawResponse == nil { - return "" - } - return r.RawResponse.Proto -} - -// Result method returns the response value as an object if it has one -func (r *Response) Result() interface{} { - return r.Request.Result -} - -// Error method returns the error object if it has one -func (r *Response) Error() interface{} { - return r.Request.Error -} - -// Header method returns the response headers -func (r *Response) Header() http.Header { - if r.RawResponse == nil { - return http.Header{} - } - return r.RawResponse.Header -} - -// Cookies method to access all the response cookies -func (r *Response) Cookies() []*http.Cookie { - if r.RawResponse == nil { - return make([]*http.Cookie, 0) - } - return r.RawResponse.Cookies() -} - -// String method returns the body of the server response as String. -func (r *Response) String() string { - if r.body == nil { - return "" - } - return strings.TrimSpace(string(r.body)) -} - -// Time method returns the time of HTTP response time that from request we sent and received a request. -// -// See `Response.ReceivedAt` to know when client received response and see `Response.Request.Time` to know -// when client sent a request. -func (r *Response) Time() time.Duration { - if r.Request.clientTrace != nil { - return r.Request.TraceInfo().TotalTime - } - return r.receivedAt.Sub(r.Request.Time) -} - -// ReceivedAt method returns when response got received from server for the request. -func (r *Response) ReceivedAt() time.Time { - return r.receivedAt -} - -// Size method returns the HTTP response size in bytes. Ya, you can relay on HTTP `Content-Length` header, -// however it won't be good for chucked transfer/compressed response. Since Resty calculates response size -// at the client end. You will get actual size of the http response. -func (r *Response) Size() int64 { - return r.size -} - -// RawBody method exposes the HTTP raw response body. Use this method in-conjunction with `SetDoNotParseResponse` -// option otherwise you get an error as `read err: http: read on closed response body`. -// -// Do not forget to close the body, otherwise you might get into connection leaks, no connection reuse. -// Basically you have taken over the control of response parsing from `Resty`. -func (r *Response) RawBody() io.ReadCloser { - if r.RawResponse == nil { - return nil - } - return r.RawResponse.Body -} - -// IsSuccess method returns true if HTTP status `code >= 200 and <= 299` otherwise false. -func (r *Response) IsSuccess() bool { - return r.StatusCode() > 199 && r.StatusCode() < 300 -} - -// IsError method returns true if HTTP status `code >= 400` otherwise false. -func (r *Response) IsError() bool { - return r.StatusCode() > 399 -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Response Unexported methods -//_______________________________________________________________________ - -func (r *Response) setReceivedAt() { - r.receivedAt = time.Now() - if r.Request.clientTrace != nil { - r.Request.clientTrace.endTime = r.receivedAt - } -} - -func (r *Response) fmtBodyString(sl int64) string { - if r.body != nil { - if int64(len(r.body)) > sl { - return fmt.Sprintf("***** RESPONSE TOO LARGE (size - %d) *****", len(r.body)) - } - ct := r.Header().Get(hdrContentTypeKey) - if IsJSONType(ct) { - out := acquireBuffer() - defer releaseBuffer(out) - err := json.Indent(out, r.body, "", " ") - if err != nil { - return fmt.Sprintf("*** Error: Unable to format response body - \"%s\" ***\n\nLog Body as-is:\n%s", err, r.String()) - } - return out.String() - } - return r.String() - } - - return "***** NO CONTENT *****" -} diff --git a/vendor/github.com/go-resty/resty/v2/resty.go b/vendor/github.com/go-resty/resty/v2/resty.go deleted file mode 100644 index 6f9c8b4c..00000000 --- a/vendor/github.com/go-resty/resty/v2/resty.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -// Package resty provides Simple HTTP and REST client library for Go. -package resty - -import ( - "net" - "net/http" - "net/http/cookiejar" - - "golang.org/x/net/publicsuffix" -) - -// Version # of resty -const Version = "2.7.0" - -// New method creates a new Resty client. -func New() *Client { - cookieJar, _ := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List}) - return createClient(&http.Client{ - Jar: cookieJar, - }) -} - -// NewWithClient method creates a new Resty client with given `http.Client`. -func NewWithClient(hc *http.Client) *Client { - return createClient(hc) -} - -// NewWithLocalAddr method creates a new Resty client with given Local Address -// to dial from. -func NewWithLocalAddr(localAddr net.Addr) *Client { - cookieJar, _ := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List}) - return createClient(&http.Client{ - Jar: cookieJar, - Transport: createTransport(localAddr), - }) -} diff --git a/vendor/github.com/go-resty/resty/v2/retry.go b/vendor/github.com/go-resty/resty/v2/retry.go deleted file mode 100644 index 00b8514a..00000000 --- a/vendor/github.com/go-resty/resty/v2/retry.go +++ /dev/null @@ -1,221 +0,0 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "context" - "math" - "math/rand" - "sync" - "time" -) - -const ( - defaultMaxRetries = 3 - defaultWaitTime = time.Duration(100) * time.Millisecond - defaultMaxWaitTime = time.Duration(2000) * time.Millisecond -) - -type ( - // Option is to create convenient retry options like wait time, max retries, etc. - Option func(*Options) - - // RetryConditionFunc type is for retry condition function - // input: non-nil Response OR request execution error - RetryConditionFunc func(*Response, error) bool - - // OnRetryFunc is for side-effecting functions triggered on retry - OnRetryFunc func(*Response, error) - - // RetryAfterFunc returns time to wait before retry - // For example, it can parse HTTP Retry-After header - // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html - // Non-nil error is returned if it is found that request is not retryable - // (0, nil) is a special result means 'use default algorithm' - RetryAfterFunc func(*Client, *Response) (time.Duration, error) - - // Options struct is used to hold retry settings. - Options struct { - maxRetries int - waitTime time.Duration - maxWaitTime time.Duration - retryConditions []RetryConditionFunc - retryHooks []OnRetryFunc - } -) - -// Retries sets the max number of retries -func Retries(value int) Option { - return func(o *Options) { - o.maxRetries = value - } -} - -// WaitTime sets the default wait time to sleep between requests -func WaitTime(value time.Duration) Option { - return func(o *Options) { - o.waitTime = value - } -} - -// MaxWaitTime sets the max wait time to sleep between requests -func MaxWaitTime(value time.Duration) Option { - return func(o *Options) { - o.maxWaitTime = value - } -} - -// RetryConditions sets the conditions that will be checked for retry. -func RetryConditions(conditions []RetryConditionFunc) Option { - return func(o *Options) { - o.retryConditions = conditions - } -} - -// RetryHooks sets the hooks that will be executed after each retry -func RetryHooks(hooks []OnRetryFunc) Option { - return func(o *Options) { - o.retryHooks = hooks - } -} - -// Backoff retries with increasing timeout duration up until X amount of retries -// (Default is 3 attempts, Override with option Retries(n)) -func Backoff(operation func() (*Response, error), options ...Option) error { - // Defaults - opts := Options{ - maxRetries: defaultMaxRetries, - waitTime: defaultWaitTime, - maxWaitTime: defaultMaxWaitTime, - retryConditions: []RetryConditionFunc{}, - } - - for _, o := range options { - o(&opts) - } - - var ( - resp *Response - err error - ) - - for attempt := 0; attempt <= opts.maxRetries; attempt++ { - resp, err = operation() - ctx := context.Background() - if resp != nil && resp.Request.ctx != nil { - ctx = resp.Request.ctx - } - if ctx.Err() != nil { - return err - } - - err1 := unwrapNoRetryErr(err) // raw error, it used for return users callback. - needsRetry := err != nil && err == err1 // retry on a few operation errors by default - - for _, condition := range opts.retryConditions { - needsRetry = condition(resp, err1) - if needsRetry { - break - } - } - - if !needsRetry { - return err - } - - for _, hook := range opts.retryHooks { - hook(resp, err) - } - - // Don't need to wait when no retries left. - // Still run retry hooks even on last retry to keep compatibility. - if attempt == opts.maxRetries { - return err - } - - waitTime, err2 := sleepDuration(resp, opts.waitTime, opts.maxWaitTime, attempt) - if err2 != nil { - if err == nil { - err = err2 - } - return err - } - - select { - case <-time.After(waitTime): - case <-ctx.Done(): - return ctx.Err() - } - } - - return err -} - -func sleepDuration(resp *Response, min, max time.Duration, attempt int) (time.Duration, error) { - const maxInt = 1<<31 - 1 // max int for arch 386 - if max < 0 { - max = maxInt - } - if resp == nil { - return jitterBackoff(min, max, attempt), nil - } - - retryAfterFunc := resp.Request.client.RetryAfter - - // Check for custom callback - if retryAfterFunc == nil { - return jitterBackoff(min, max, attempt), nil - } - - result, err := retryAfterFunc(resp.Request.client, resp) - if err != nil { - return 0, err // i.e. 'API quota exceeded' - } - if result == 0 { - return jitterBackoff(min, max, attempt), nil - } - if result < 0 || max < result { - result = max - } - if result < min { - result = min - } - return result, nil -} - -// Return capped exponential backoff with jitter -// http://www.awsarchitectureblog.com/2015/03/backoff.html -func jitterBackoff(min, max time.Duration, attempt int) time.Duration { - base := float64(min) - capLevel := float64(max) - - temp := math.Min(capLevel, base*math.Exp2(float64(attempt))) - ri := time.Duration(temp / 2) - result := randDuration(ri) - - if result < min { - result = min - } - - return result -} - -var rnd = newRnd() -var rndMu sync.Mutex - -func randDuration(center time.Duration) time.Duration { - rndMu.Lock() - defer rndMu.Unlock() - - var ri = int64(center) - var jitter = rnd.Int63n(ri) - return time.Duration(math.Abs(float64(ri + jitter))) -} - -func newRnd() *rand.Rand { - var seed = time.Now().UnixNano() - var src = rand.NewSource(seed) - return rand.New(src) -} diff --git a/vendor/github.com/go-resty/resty/v2/trace.go b/vendor/github.com/go-resty/resty/v2/trace.go deleted file mode 100644 index 23cf7033..00000000 --- a/vendor/github.com/go-resty/resty/v2/trace.go +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "context" - "crypto/tls" - "net" - "net/http/httptrace" - "time" -) - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// TraceInfo struct -//_______________________________________________________________________ - -// TraceInfo struct is used provide request trace info such as DNS lookup -// duration, Connection obtain duration, Server processing duration, etc. -// -// Since v2.0.0 -type TraceInfo struct { - // DNSLookup is a duration that transport took to perform - // DNS lookup. - DNSLookup time.Duration - - // ConnTime is a duration that took to obtain a successful connection. - ConnTime time.Duration - - // TCPConnTime is a duration that took to obtain the TCP connection. - TCPConnTime time.Duration - - // TLSHandshake is a duration that TLS handshake took place. - TLSHandshake time.Duration - - // ServerTime is a duration that server took to respond first byte. - ServerTime time.Duration - - // ResponseTime is a duration since first response byte from server to - // request completion. - ResponseTime time.Duration - - // TotalTime is a duration that total request took end-to-end. - TotalTime time.Duration - - // IsConnReused is whether this connection has been previously - // used for another HTTP request. - IsConnReused bool - - // IsConnWasIdle is whether this connection was obtained from an - // idle pool. - IsConnWasIdle bool - - // ConnIdleTime is a duration how long the connection was previously - // idle, if IsConnWasIdle is true. - ConnIdleTime time.Duration - - // RequestAttempt is to represent the request attempt made during a Resty - // request execution flow, including retry count. - RequestAttempt int - - // RemoteAddr returns the remote network address. - RemoteAddr net.Addr -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// ClientTrace struct and its methods -//_______________________________________________________________________ - -// tracer struct maps the `httptrace.ClientTrace` hooks into Fields -// with same naming for easy understanding. Plus additional insights -// Request. -type clientTrace struct { - getConn time.Time - dnsStart time.Time - dnsDone time.Time - connectDone time.Time - tlsHandshakeStart time.Time - tlsHandshakeDone time.Time - gotConn time.Time - gotFirstResponseByte time.Time - endTime time.Time - gotConnInfo httptrace.GotConnInfo -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Trace unexported methods -//_______________________________________________________________________ - -func (t *clientTrace) createContext(ctx context.Context) context.Context { - return httptrace.WithClientTrace( - ctx, - &httptrace.ClientTrace{ - DNSStart: func(_ httptrace.DNSStartInfo) { - t.dnsStart = time.Now() - }, - DNSDone: func(_ httptrace.DNSDoneInfo) { - t.dnsDone = time.Now() - }, - ConnectStart: func(_, _ string) { - if t.dnsDone.IsZero() { - t.dnsDone = time.Now() - } - if t.dnsStart.IsZero() { - t.dnsStart = t.dnsDone - } - }, - ConnectDone: func(net, addr string, err error) { - t.connectDone = time.Now() - }, - GetConn: func(_ string) { - t.getConn = time.Now() - }, - GotConn: func(ci httptrace.GotConnInfo) { - t.gotConn = time.Now() - t.gotConnInfo = ci - }, - GotFirstResponseByte: func() { - t.gotFirstResponseByte = time.Now() - }, - TLSHandshakeStart: func() { - t.tlsHandshakeStart = time.Now() - }, - TLSHandshakeDone: func(_ tls.ConnectionState, _ error) { - t.tlsHandshakeDone = time.Now() - }, - }, - ) -} diff --git a/vendor/github.com/go-resty/resty/v2/transport.go b/vendor/github.com/go-resty/resty/v2/transport.go deleted file mode 100644 index e15b48c5..00000000 --- a/vendor/github.com/go-resty/resty/v2/transport.go +++ /dev/null @@ -1,35 +0,0 @@ -// +build go1.13 - -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "net" - "net/http" - "runtime" - "time" -) - -func createTransport(localAddr net.Addr) *http.Transport { - dialer := &net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - DualStack: true, - } - if localAddr != nil { - dialer.LocalAddr = localAddr - } - return &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: dialer.DialContext, - ForceAttemptHTTP2: true, - MaxIdleConns: 100, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1, - } -} diff --git a/vendor/github.com/go-resty/resty/v2/transport112.go b/vendor/github.com/go-resty/resty/v2/transport112.go deleted file mode 100644 index fbbbc591..00000000 --- a/vendor/github.com/go-resty/resty/v2/transport112.go +++ /dev/null @@ -1,34 +0,0 @@ -// +build !go1.13 - -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "net" - "net/http" - "runtime" - "time" -) - -func createTransport(localAddr net.Addr) *http.Transport { - dialer := &net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - DualStack: true, - } - if localAddr != nil { - dialer.LocalAddr = localAddr - } - return &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: dialer.DialContext, - MaxIdleConns: 100, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1, - } -} diff --git a/vendor/github.com/go-resty/resty/v2/util.go b/vendor/github.com/go-resty/resty/v2/util.go deleted file mode 100644 index 1d563bef..00000000 --- a/vendor/github.com/go-resty/resty/v2/util.go +++ /dev/null @@ -1,391 +0,0 @@ -// Copyright (c) 2015-2021 Jeevanandam M (jeeva@myjeeva.com), All rights reserved. -// resty source code and usage is governed by a MIT style -// license that can be found in the LICENSE file. - -package resty - -import ( - "bytes" - "fmt" - "io" - "log" - "mime/multipart" - "net/http" - "net/textproto" - "os" - "path/filepath" - "reflect" - "runtime" - "sort" - "strings" - "sync" -) - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Logger interface -//_______________________________________________________________________ - -// Logger interface is to abstract the logging from Resty. Gives control to -// the Resty users, choice of the logger. -type Logger interface { - Errorf(format string, v ...interface{}) - Warnf(format string, v ...interface{}) - Debugf(format string, v ...interface{}) -} - -func createLogger() *logger { - l := &logger{l: log.New(os.Stderr, "", log.Ldate|log.Lmicroseconds)} - return l -} - -var _ Logger = (*logger)(nil) - -type logger struct { - l *log.Logger -} - -func (l *logger) Errorf(format string, v ...interface{}) { - l.output("ERROR RESTY "+format, v...) -} - -func (l *logger) Warnf(format string, v ...interface{}) { - l.output("WARN RESTY "+format, v...) -} - -func (l *logger) Debugf(format string, v ...interface{}) { - l.output("DEBUG RESTY "+format, v...) -} - -func (l *logger) output(format string, v ...interface{}) { - if len(v) == 0 { - l.l.Print(format) - return - } - l.l.Printf(format, v...) -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Package Helper methods -//_______________________________________________________________________ - -// IsStringEmpty method tells whether given string is empty or not -func IsStringEmpty(str string) bool { - return len(strings.TrimSpace(str)) == 0 -} - -// DetectContentType method is used to figure out `Request.Body` content type for request header -func DetectContentType(body interface{}) string { - contentType := plainTextType - kind := kindOf(body) - switch kind { - case reflect.Struct, reflect.Map: - contentType = jsonContentType - case reflect.String: - contentType = plainTextType - default: - if b, ok := body.([]byte); ok { - contentType = http.DetectContentType(b) - } else if kind == reflect.Slice { - contentType = jsonContentType - } - } - - return contentType -} - -// IsJSONType method is to check JSON content type or not -func IsJSONType(ct string) bool { - return jsonCheck.MatchString(ct) -} - -// IsXMLType method is to check XML content type or not -func IsXMLType(ct string) bool { - return xmlCheck.MatchString(ct) -} - -// Unmarshalc content into object from JSON or XML -func Unmarshalc(c *Client, ct string, b []byte, d interface{}) (err error) { - if IsJSONType(ct) { - err = c.JSONUnmarshal(b, d) - } else if IsXMLType(ct) { - err = c.XMLUnmarshal(b, d) - } - - return -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// RequestLog and ResponseLog type -//_______________________________________________________________________ - -// RequestLog struct is used to collected information from resty request -// instance for debug logging. It sent to request log callback before resty -// actually logs the information. -type RequestLog struct { - Header http.Header - Body string -} - -// ResponseLog struct is used to collected information from resty response -// instance for debug logging. It sent to response log callback before resty -// actually logs the information. -type ResponseLog struct { - Header http.Header - Body string -} - -//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ -// Package Unexported methods -//_______________________________________________________________________ - -// way to disable the HTML escape as opt-in -func jsonMarshal(c *Client, r *Request, d interface{}) (*bytes.Buffer, error) { - if !r.jsonEscapeHTML || !c.jsonEscapeHTML { - return noescapeJSONMarshal(d) - } - - data, err := c.JSONMarshal(d) - if err != nil { - return nil, err - } - - buf := acquireBuffer() - _, _ = buf.Write(data) - return buf, nil -} - -func firstNonEmpty(v ...string) string { - for _, s := range v { - if !IsStringEmpty(s) { - return s - } - } - return "" -} - -var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"") - -func escapeQuotes(s string) string { - return quoteEscaper.Replace(s) -} - -func createMultipartHeader(param, fileName, contentType string) textproto.MIMEHeader { - hdr := make(textproto.MIMEHeader) - - var contentDispositionValue string - if IsStringEmpty(fileName) { - contentDispositionValue = fmt.Sprintf(`form-data; name="%s"`, param) - } else { - contentDispositionValue = fmt.Sprintf(`form-data; name="%s"; filename="%s"`, - param, escapeQuotes(fileName)) - } - hdr.Set("Content-Disposition", contentDispositionValue) - - if !IsStringEmpty(contentType) { - hdr.Set(hdrContentTypeKey, contentType) - } - return hdr -} - -func addMultipartFormField(w *multipart.Writer, mf *MultipartField) error { - partWriter, err := w.CreatePart(createMultipartHeader(mf.Param, mf.FileName, mf.ContentType)) - if err != nil { - return err - } - - _, err = io.Copy(partWriter, mf.Reader) - return err -} - -func writeMultipartFormFile(w *multipart.Writer, fieldName, fileName string, r io.Reader) error { - // Auto detect actual multipart content type - cbuf := make([]byte, 512) - size, err := r.Read(cbuf) - if err != nil && err != io.EOF { - return err - } - - partWriter, err := w.CreatePart(createMultipartHeader(fieldName, fileName, http.DetectContentType(cbuf))) - if err != nil { - return err - } - - if _, err = partWriter.Write(cbuf[:size]); err != nil { - return err - } - - _, err = io.Copy(partWriter, r) - return err -} - -func addFile(w *multipart.Writer, fieldName, path string) error { - file, err := os.Open(path) - if err != nil { - return err - } - defer closeq(file) - return writeMultipartFormFile(w, fieldName, filepath.Base(path), file) -} - -func addFileReader(w *multipart.Writer, f *File) error { - return writeMultipartFormFile(w, f.ParamName, f.Name, f.Reader) -} - -func getPointer(v interface{}) interface{} { - vv := valueOf(v) - if vv.Kind() == reflect.Ptr { - return v - } - return reflect.New(vv.Type()).Interface() -} - -func isPayloadSupported(m string, allowMethodGet bool) bool { - return !(m == MethodHead || m == MethodOptions || (m == MethodGet && !allowMethodGet)) -} - -func typeOf(i interface{}) reflect.Type { - return indirect(valueOf(i)).Type() -} - -func valueOf(i interface{}) reflect.Value { - return reflect.ValueOf(i) -} - -func indirect(v reflect.Value) reflect.Value { - return reflect.Indirect(v) -} - -func kindOf(v interface{}) reflect.Kind { - return typeOf(v).Kind() -} - -func createDirectory(dir string) (err error) { - if _, err = os.Stat(dir); err != nil { - if os.IsNotExist(err) { - if err = os.MkdirAll(dir, 0755); err != nil { - return - } - } - } - return -} - -func canJSONMarshal(contentType string, kind reflect.Kind) bool { - return IsJSONType(contentType) && (kind == reflect.Struct || kind == reflect.Map || kind == reflect.Slice) -} - -func functionName(i interface{}) string { - return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name() -} - -func acquireBuffer() *bytes.Buffer { - return bufPool.Get().(*bytes.Buffer) -} - -func releaseBuffer(buf *bytes.Buffer) { - if buf != nil { - buf.Reset() - bufPool.Put(buf) - } -} - -// requestBodyReleaser wraps requests's body and implements custom Close for it. -// The Close method closes original body and releases request body back to sync.Pool. -type requestBodyReleaser struct { - releaseOnce sync.Once - reqBuf *bytes.Buffer - io.ReadCloser -} - -func newRequestBodyReleaser(respBody io.ReadCloser, reqBuf *bytes.Buffer) io.ReadCloser { - if reqBuf == nil { - return respBody - } - - return &requestBodyReleaser{ - reqBuf: reqBuf, - ReadCloser: respBody, - } -} - -func (rr *requestBodyReleaser) Close() error { - err := rr.ReadCloser.Close() - rr.releaseOnce.Do(func() { - releaseBuffer(rr.reqBuf) - }) - - return err -} - -func closeq(v interface{}) { - if c, ok := v.(io.Closer); ok { - silently(c.Close()) - } -} - -func silently(_ ...interface{}) {} - -func composeHeaders(c *Client, r *Request, hdrs http.Header) string { - str := make([]string, 0, len(hdrs)) - for _, k := range sortHeaderKeys(hdrs) { - var v string - if k == "Cookie" { - cv := strings.TrimSpace(strings.Join(hdrs[k], ", ")) - if c.GetClient().Jar != nil { - for _, c := range c.GetClient().Jar.Cookies(r.RawRequest.URL) { - if cv != "" { - cv = cv + "; " + c.String() - } else { - cv = c.String() - } - } - } - v = strings.TrimSpace(fmt.Sprintf("%25s: %s", k, cv)) - } else { - v = strings.TrimSpace(fmt.Sprintf("%25s: %s", k, strings.Join(hdrs[k], ", "))) - } - if v != "" { - str = append(str, "\t"+v) - } - } - return strings.Join(str, "\n") -} - -func sortHeaderKeys(hdrs http.Header) []string { - keys := make([]string, 0, len(hdrs)) - for key := range hdrs { - keys = append(keys, key) - } - sort.Strings(keys) - return keys -} - -func copyHeaders(hdrs http.Header) http.Header { - nh := http.Header{} - for k, v := range hdrs { - nh[k] = v - } - return nh -} - -type noRetryErr struct { - err error -} - -func (e *noRetryErr) Error() string { - return e.err.Error() -} - -func wrapNoRetryErr(err error) error { - if err != nil { - err = &noRetryErr{err: err} - } - return err -} - -func unwrapNoRetryErr(err error) error { - if e, ok := err.(*noRetryErr); ok { - err = e.err - } - return err -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 6b2b19f0..19f48071 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -34,6 +34,15 @@ github.com/cespare/xxhash/v2 # github.com/chzyer/readline v1.5.1 ## explicit; go 1.15 github.com/chzyer/readline +# github.com/cloudbase/garm-provider-common v0.0.0-20230724114054-7aa0a3dfbce0 +## explicit; go 1.20 +github.com/cloudbase/garm-provider-common/cloudconfig +github.com/cloudbase/garm-provider-common/defaults +github.com/cloudbase/garm-provider-common/errors +github.com/cloudbase/garm-provider-common/execution +github.com/cloudbase/garm-provider-common/params +github.com/cloudbase/garm-provider-common/util +github.com/cloudbase/garm-provider-common/util/exec # github.com/cloudflare/circl v1.3.3 ## explicit; go 1.19 github.com/cloudflare/circl/dh/x25519 @@ -120,9 +129,6 @@ github.com/go-openapi/swag # github.com/go-openapi/validate v0.22.1 ## explicit; go 1.14 github.com/go-openapi/validate -# github.com/go-resty/resty/v2 v2.7.0 -## explicit; go 1.11 -github.com/go-resty/resty/v2 # github.com/go-sql-driver/mysql v1.7.0 ## explicit; go 1.13 github.com/go-sql-driver/mysql @@ -219,7 +225,7 @@ github.com/mailru/easyjson/jwriter github.com/manifoldco/promptui github.com/manifoldco/promptui/list github.com/manifoldco/promptui/screenbuf -# github.com/mattn/go-isatty v0.0.18 +# github.com/mattn/go-isatty v0.0.19 ## explicit; go 1.15 github.com/mattn/go-isatty # github.com/mattn/go-runewidth v0.0.14